2016-03-29 4 views
1

私は現在、私の頭を包むことができないものがあります。 私は、各要素が1だけインクリメントされる出力を期待していました。 明らかにそうではありません。for_eachループでbind2nd

もっと見ると、bind2nd関数の戻り値が破棄されたためです。つまり、関数はコンテナの要素を変更しません。

私の考えは正しいですか?誰かが修正されていない容器について正しい説明を確認したり提供したりすることはできますか?

#include <vector> 
#include <iostream> 
#include <algorithm> 
#include <functional> using namespace std; void printer(int i) { 
     cout << i << ", "; } int main() { 
     int mynumbers[] = { 8, 9, 7, 6, 4, 1 }; 
     vector<int> v1(mynumbers, mynumbers + 6); 
     for_each(v1.begin(), v1.end(), bind2nd(plus<int>(), 1));//LINE I 
     for_each(v1.rbegin(), v1.rend(), printer);//LINE II 
     return 0; } 

答えて

1
for_each(v1.begin(), v1.end(), bind2nd(plus<int>(), 1)); 

が同等ですそれは確かに何も変わらないでしょう。

あなたはstd::for_eachで値を変更ファンクタ使用することができます

std::for_each(v1.begin(), v1.end(), [](int &n){ n += 1; }); 
1

std::for_each入力シーケンスは変更されません。

代わりstd::transformを使用し、容器の各要素に変更を適用する:

transform(v1.begin(), v1.end(), v1.begin(), bind2nd(plus<int>(), 1)); 
//        ~~~~~~~~~^ puts the results back into the input sequence 
2

template <typename T> std::plusoperator()の宣言はすなわち、それは入力引数を変更しない

T operator()(const T& lhs, const T& rhs) const; 

あります。

std::transform(v1.cbegin(), v1.cend() v1.begin(), std::bind2nd(std::plus<int>(), 1)); 

またはあなたがどのは、入力引数の変更んラムダを使用することができます:あなたはstd::transform必要

for (auto first = v1.begin(); first != last; ++first) { 
    plus<int>()(*first, 1); // i.e. *first + 1; 
} 

あなたが見られるように:として

std::for_each(v1.begin(), v1.end(), [] (int& x) { ++x; }); 
関連する問題