std::vector で参照を保持したい
std::vector<T&>
みたいに std::vector
で参照値を保持したい事があると思いますが、これはコンパイルエラーになってしまいます。
この問題を回避したい場合は、C++11 で追加された std::reference_wrapper
を利用する事ができます。
[コード]
#include <vector> #include <functional> #include <iostream> int main(){ // std::vector<int&> values; // これはエラー std::vector<std::reference_wrapper<int>> values; int a = 0; int b = 0; int c = 0; values.push_back(a); values.push_back(b); values.push_back(c); values[0].get() = 1; values[1].get() = 2; values[2].get() = 3; std::cout << a << std::endl; std::cout << b << std::endl; std::cout << c << std::endl; return 0; }
[出力]
1 2 3
値を代入するときに get()
を使う必要があるのがちょっとめんどいですかねぇ。