Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increment all C++ std::vector values by a constant value

Tags:

c++

vector

I am trying to figure out what is the best way to increment all the elements of an std::vector<int> with a constant int value.

In other words, if I have a vector with elements: 1 2 3 4 5

I want to do something like

vect += 5;

So the elements will be: 6 7 8 9 10.

I tried to overload operator += but it turns out I don't know how to do it :S I tried this:

std::vector<int> & operator += (const int & increment) {
    for (int &i : *this)
        *this[i] = *this[i] + increment;
}

And this compiles, but whenever I use it I get this error:

no match for ‘operator+=’ (operand types are ‘std::vector<int>’ and ‘int’)
 vec += 3;
        ^

Any advice? I would like to do it this way instead of a regular increment(vector, value) function.

Thank you!

like image 892
Javi Avatar asked Sep 10 '26 22:09

Javi


2 Answers

Don't try to change the behaviour of std::vector; this is not allowed by the language.

Instead use std::valarray, which already has support for broadcasting addition and other operations.

like image 181
ecatmur Avatar answered Sep 12 '26 12:09

ecatmur


As mentioned before, don't try to add new functions to std::vector, you are not allowed to. The standard says you can only open the std:: namespace to specialize existing template code for an user-defined type. There is operator+= for std::vector and int is not an user-defined type.

So you can't do what you want (even if it may technically works) it is not legal.

Instead, use std::transform or std::for_each

#include <iostream>
#include <vector>
#include <algorithm>

int main(void) {
    std::vector<int> v={{1,2,3,4,5}};
    std::transform(std::begin(v),std::end(v),std::begin(v),[](int x){return x+5;});
    for(auto e :v)
    {
        std::cout<<e<<std::endl;
    }
    return 0;
}
like image 20
Davidbrcz Avatar answered Sep 12 '26 12:09

Davidbrcz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!