boost::向量中元素的变体和打印方法
std::vector< boost::variant<std::string, int> > vec;
std::string s1("abacus");
int i1 = 42;
vec.push_back(s1);
vec.push_back(i1);
std::cout << vec.at(0).size() << "\n";
当我尝试运行此代码时,出现以下错误:
main.cpp:68: error: ‘class boost::variant<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_>’ has no member named ‘size’
make: *** [main.o] Error 1
但是,作为字符串,它应该有一个 size() 方法。我不确定出了什么问题。请注意,将最后一行替换为:
std::cout << vec.at(0) << "\n";
将按预期打印“abacus”。
std::vector< boost::variant<std::string, int> > vec;
std::string s1("abacus");
int i1 = 42;
vec.push_back(s1);
vec.push_back(i1);
std::cout << vec.at(0).size() << "\n";
when I try to run this code, I get the following error:
main.cpp:68: error: ‘class boost::variant<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_>’ has no member named ‘size’
make: *** [main.o] Error 1
however, being a string it should have a size() method. I'm not sure what is going wrong. note that replacing the last line with:
std::cout << vec.at(0) << "\n";
will print "abacus", as expected.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它不是一个
字符串
——它是一个变体
。您首先需要告诉编译器您知道里面有一个字符串
- 即使用boost::get(vec [0])
。请务必阅读 Boost。变体教程。
It’s not a
string
– it’s avariant
. You first need to tell the compiler that you know there’s astring
inside – i.e. retrieve it usingboost::get<std::string>(vec[0])
.Be sure to read the Boost.Variant tutorial.
您需要获取此变体的第一种类型(即字符串),您使用
vector::at()
访问的类boost::variant
没有名为size()
的方法,请尝试以下操作::You need to get the first type of this variant (which is the string), the class
boost::variant
which you are accessing withvector::at()
has no method calledsize()
, try something like::