我想知道什麼是增加std::vector<int>
的所有元素的最佳方法,其值爲常量int
值。將所有C++ std ::向量值增加一個常數值
換句話說,如果我有一個元素的向量:1 2 3 4 5
我要像做
vect += 5;
這樣的元素將是:6 7 8 9 10
。
我試圖重載operator +=
但事實證明,我不知道如何做到這一點:SI試過這樣:
std::vector<int> & operator += (const int & increment) {
for (int &i : *this)
*this[i] = *this[i] + increment;
}
這編譯,但每當我使用它,我得到這個錯誤:
no match for ‘operator+=’ (operand types are ‘std::vector<int>’ and ‘int’)
vec += 3;
^
有什麼建議嗎?我想這樣做,而不是常規的increment(vector, value)
函數。
謝謝!
如果你想繼續使用'的std :: VECTOR',C++標準庫中有很多不錯的[算法](http://en.cppreference.com/W/CPP /算法)。爲此,最好的可能是['std :: transform'](http://en.cppreference.com/w/cpp/algorithm/transform)。 –
或'std :: for_each'。然而,在實踐中,如果提問者不想複製和粘貼他們已經編寫的基於範圍的for循環,那麼他們可能不希望將調用複製並粘貼到算法。我認爲這個問題是關於*減少*樣板,也許超出了C++舒適支持的範圍:-) –
@JoachimPileborg另外'std :: transform'不一定是線性的,並且可能比自定義線性'for'循環或者'std :: for_each'。 – Etherealone