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

c++, vector

Solution

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;
}

Problem

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!

Original source