我正在尝试这样做:维护两个字符串 vector ,其中一个 vector 存储值,第二个 vector 存储相同值的引用。我认为使用 boost::reference_wrapper
可以解决问题,但似乎不会。我的平台是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);
}
这是错误:
error C2664: 'std::vector<_Ty>::push_back' : cannot convert parameter 1 from std::basic_string<_Elem,_Traits,_Ax>' to 'const boost::reference
我可以使用 boost::shared_ptr
但我认为引用更好地表达了我的意图。这段代码可能可以在 C++11 中使用 std::reference_wrapper
运行,但我现在无法使用。
最佳答案
是的,可以。文档指出它是CopyConstructible
和Assignable
,这是容器模板参数必需的概念。但您需要使用 boost::ref
或 boost::cref
来创建 reference_wrapper
类型的对象。没有隐式转换,这就是您的代码不起作用的原因。
请注意,std::reference_wrapper
和 boost::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));
虽然我不会那样做。
关于c++ - 可以使用 boost::reference_wrapper 将引用存储在 STL 容器中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10272005/