2014-01-30 67 views
0

我想知道什麼是增加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)函數。

謝謝!

+3

如果你想繼續使用'的std :: VECTOR',C++標準庫中有很多不錯的[算法](http://en.cppreference.com/W/CPP /算法)。爲此,最好的可能是['std :: transform'](http://en.cppreference.com/w/cpp/algorithm/transform)。 –

+0

或'std :: for_each'。然而,在實踐中,如果提問者不想複製和粘貼他們已經編寫的基於範圍的for循環,那麼他們可能不希望將調用複製並粘貼到算法。我認爲這個問題是關於*減少*樣板,也許超出了C++舒適支持的範圍:-) –

+1

@JoachimPileborg另外'std :: transform'不一定是線性的,並且可能比自定義線性'for'循環或者'std :: for_each'。 – Etherealone

回答

0

如前所述,不要試圖添加新功能到std::vector,你是不允許的。 該標準說明您只能打開std::名稱空間來專門爲現有模板代碼爲用戶定義的類型。有運算符+ = std :: vector和int不是用戶定義的類型。

所以你不能做你想做的事(即使它在技術上可行),這是不合法的。

相反,使用std::transformstd::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; 
} 
+0

我認爲將矢量value_type硬編碼到lambda中並不是一個好主意,特別是如果您將它稱爲距矢量聲明很遠的話。使用'decltype(v):: value_type x'而不是'int x'更安全:如果您決定更改矢量類型,它將自動調整。 – DarioP

2

您不能修改std::vector,但在技術上沒有什麼能夠阻止你編寫自己的(全球)過載operator+=爲載體和整型:

vector<int>& operator+=(vector<int>& v, int x) { 
    for (auto a=begin(v); a!=end(v); ++a) { 
     *a += x; 
    } 
    return v; 
} 

演示:http://ideone.com/kKXnWS

但是,編寫過載對於std類既不是直接的,也不是解決問題的標準方法。我推薦使用@ecatmur's solution with std::valarraystd::transform代替Joachim Pileborg's recommendation

+0

好回答Kos – hims

+0

謝謝你的迴應。然而,看起來valarray可能比轉換效率更高......但如果我必須稍後轉換爲矢量,那麼值得嗎? –