c++ - 如何打印使用“std::any”类型的变量插入的字符串向量的元素
问题描述
这是我的 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::bad_any_cast
在尝试std::string
从std::any
.
你可以改变得到const char*
喜欢
a.insert(a.begin(),any_cast<const char*>(x));
std::string
或从头开始分配std::any
。
x=std::string("Hello");
或使用文字(C++14 起)
x="Hello"s;
推荐阅读
- javascript - 如何修复 HasAttributes.php 中的 ErrorException
- ionic-framework - Ionic 4:我正在使用 Document Viewer 查看 pdf 文件。但它不工作
- android - 用于使用 Picasso 显示来自 URL 的图像的绑定适配器
- python - 我正在尝试创建一个对象,但应该工作的代码不起作用
- android-studio - 如果没有明确的 null 检查,编译器将无法识别不可为 null 的值
- html - CSS :active 仅在点击期间有效
- angular - 如何在离子的选项卡组件内路由
- sql - 如何在Group By sql中选择最小值行
- ef-code-first - 代码首先不运行所有迁移
- python - 选择性 Pandas dropna 使 DataFrame 的长度不同