我想把数组中的元素从索引A修改为索引B。
示例:我有一个数组[0,0,0,0,0]。我希望将索引1到2之间的元素按1递增,这样在操作结束时数组将为[0,1,1,0,0]。有没有更好的方法来做到这一点,而不是循环遍历数组并逐一修改它们?
我将把这个应用到一个大数组上,所以如果有一种方法可以做到这一点,而不使用循环,那将是最好的。
样品:
#include <bits/stdc++.h>
using namespace std;
int main() {
// initialisation
int arr[5];
int first_indx = 1, last_indx = 2;
fill(arr, arr + 5, 0);
cout << "Initial: \n";
for (int a : arr) {
cout << a << ", ";
}
cout << "\n";
// operation to modify array
for (int b = 0; b < 5; b++) {
if (first_indx <= b && b <= last_indx) {
arr[b]++;
}
}
// output
cout << "After modification: \n";
for (int c : arr) {
cout << c << ", ";
}
}
输出:
Initial:
0, 0, 0, 0, 0,
After modification:
0, 1, 1, 0, 0,
只在要修改的范围内循环比在整个数组之间循环要好。
// operation to modify array
for (int b = first_indx; b <= last_indx; b++) {
arr[b]++;
}
你为什么要重复整件事?
for (int b = first_indx ; b <= last_indx; b++) {
arr[b]++;
}
注意:
我感觉您正在解决一些比您想象的更具挑战性的联机任务(有许多范围进行此修改)。你的野蛮武力解决方案将不会获得最大的结果,即使当你应用了fix from Answers。
您可以使用循环,正如其他人指出的那样,您不需要迭代整个范围,只是为了跳过所需范围之外的元素。在您的代码中已经存在一种实现相同功能的不同方法:
fill(arr, arr + 5, 0);
这将用0
填充从第一个(arr
衰减到指向此处第一个元素的指针)到最后一个(arr+5
)的元素。要在不同的范围内分配不同的值,可以使用相同的算法:
int start = 1;
int end = 3;
std::fill(arr + start, arr + end, 1);
确保范围有效(未超出数组的界限)。注意,我使用了半开放范围,即包括start
,不包括end
,因为这样做是常见的惯例。