这是我的 C++ 代码的主要功能。
int main() {
vector<string> a;
any x;
x="Hello";
a.insert(a.begin(),any_cast<string>(x));
cout<<a[0]<<endl;
}
这给了我一个像这样的错误:
terminate called after throwing an instance of 'std::bad_any_cast'
what(): bad any_cast
Aborted (core dumped)
最佳答案
问题是,"Hello"
的类型为 const char[6]
并且会衰减为 const char*
,它不是 std::string
。这就是为什么当您尝试从 std::any
获取 std::string
时,会得到 std::bad_any_cast
。
您可以更改为获取const char*
,例如
a.insert(a.begin(),any_cast<const char*>(x));
或者从头开始将 std::string
分配给 std::any
。
x=std::string("Hello");
或者使用literals (自 C++14 起)
x="Hello"s;
关于c++ - 如何打印使用 "std::any"类型的变量插入的字符串 vector 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62570666/