2012-04-22 13 views
1

私はこれをやろうとしています:2つのベクトルのベクトルを1つのベクトルが値を格納し、2つ目のベクトルが同じ値の参照を格納するようにします。私はboost::reference_wrapperを使用してトリックを行うと思ったが、それはそう思わない。私はboost::shared_ptrを使用することができboost :: reference_wrapperを使用してSTLコンテナに参照を格納できますか?

error C2664: 'std::vector<_Ty>::push_back' : cannot convert parameter 1 from std::basic_string<_Elem,_Traits,_Ax>' to 'const boost::reference

が、私は、参照はより良い私の意図を表現すると思った:私のプラットフォームは、Visual C++ 2008

std::vector<std::string> str_vec; 
str_vec.push_back("abc"); 
str_vec.push_back("cde"); 
str_vec.push_back("fgh"); 

std::vector<boost::reference_wrapper<std::string> > str_view; 
for(std::vector<std::string>::iterator it = str_vec.begin(); it != str_vec.end(); ++it) 
{ 
    str_view.push_back(*it); 
} 

ですこれはエラーです。このコードはおそらくstd::reference_wrapperを使用してC++ 11で動作する可能性がありますが、それは私には現在利用できません。

+1

visual C++ 2009とは何ですか?私が知る限り、2008年、2010年、2011年のベータ版があります。 – EdChum

答えて

2

はい、可能です。ドキュメントには、コンテナテンプレートの引数として必要な概念であるCopyConstructibleAssignableが記載されています。しかしreference_wrapperのオブジェクトを作成するには、boost::refまたはboost::crefを使用する必要があります。暗黙的な変換がないため、コードが機能しません。

std::reference_wrapperboost::reference_wrapperの間に若干の違いがあるのは、stdバージョンのみがファンクタで動作することです。

例:

std::vector<std::string> str_vec; 
str_vec.push_back("abc"); 
str_vec.push_back("cde"); 
str_vec.push_back("fgh"); 

std::vector<boost::reference_wrapper<std::string> > str_view; 
std::transform(begin(str_vec), end(str_vec), 
       std::back_inserter(str_view), boost::ref<std::string>); 

あなたはそれを嫌うし、元の値からの暗黙的な変換を持っているしたい場合は、使用することをお勧めします:

template<typename T> 
class my_ref_wrap : public boost::reference_wrapper<T> { 
public: 
    my_ref_wrap(T& t) : boost::reference_wrapper<T>(t) {} 
}; 

std::vector<my_ref_wrap<std::string> > str_view; 
std::copy(begin(str_vec), begin(str_vec), 
      std::back_inserter(str_view)); 

私はそれをしないだろうが。

+0

あなたはC++ 03の例を入れてもいいですか?私はC++ 11コンパイラを持っていません – user841550

+0

@ user841550これは基本的にC++ 03です。 'begin(str_vec)'を 'str_vec.begin()'に変更するだけです。 'end()'と同様です。 – pmr

+0

私はそれをありがとう。 – user841550

関連する問題