Home > other >  Is there a fast way to modify all the elements of a vector by given value?
Is there a fast way to modify all the elements of a vector by given value?

Time:11-11

Basically the title. Is there a relatively fast way to modify all, or a bunch of elements of a vector by a given value, for eg. 1? If not, is there some other datatype that would perform this kind of an operation better?

I have implemented a for loop that basically adds 1 to every element of a vector. Is there some cleaner/shorter way to go about this?

vector<int> vct;
for (int i = 0;i<10;i  ){
    vct.push_back(i);
}
for (int i = 0;i<vct.size();i  ){
    vct[i]  ;
}

CodePudding user response:

You would need to check if the compiler does not already optimize it. Run the compiler with optimization on (-O3 on clang and g for example) and check the assembly code code.

Clang for example does some optimizations on vectors already, and without meassuring, you will not know if your code will be slower or faster. https://llvm.org/docs/Vectorizers.html

So make sure to measure if you want to know if your optimizations have effect.

My syntax favorite is like a commenter above

for (auto &x: vec) {
    x .. something
}

CodePudding user response:

One possibility is to use a data structure which combines a scalar offset, base, and a vector of numbers, data. The value of element i is then computed as base data[i], which is still O(1). (On modern CPUs, you probably won't notice the time taken by the addition.)

To increment an individual element, you simply increment the particular value in data. To increment all elements, you can increment base.

If you need to set element i to a specific value v, you can use data[i] = v - base. But normally this data structure is used for problems where the data is always incremented (or decremented), either individually or collectively, and it is desired to make collective increments O(1).

  • Related