c++ - C++ std::vector::emplace_back 不能用字符串值类编译
问题描述
/* Item.h */
struct Item {
std::string name;
Item(std::string _name) : name( std::move(_name) ) { }
};
/* main.cpp */
/* ... */
const int amount_of_items = val.size();
std::vector<Item> items(amount_of_items);
for( Json::Value::const_iterator itr = val.begin() ; itr != val.end() ; ++itr ) {
items.emplace_back( "item_name" );
}
结果是:
/usr/include/c++/8/bits/stl_construct.h:75:7: error: no matching function for call to ‘Item::Item()’
{ ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In file included from main.cpp:8: Item.h:8:2: note: candidate: ‘Item::Item(std::__cxx11::string)’ Item(std::string _name) : name( std::move(_name) ) { } ^~~~ Item.h:8:2: note: candidate expects 1 argument, 0 provided
我不知道为什么这行不通-有什么想法吗?
解决方案
这个说法:
std::vector<Item> items(amount_of_items);
需要默认构造函数,因为您已要求编译器使用默认构造的 sItem
填充数组。amount_of_items
Item
相反,您需要简单地编写:
std::vector<Item> items;
因为emplace_back
将根据需要增加数组。
请注意,如果您想预先为您的 s 预留空间,您可以致电。items.reserve
Item
推荐阅读
- ios - 与迦太基一起跳到源头
- c# - 将 WebProxy 用于我无法控制的 HttpClient
- wordpress - 从帖子内容中的html标签中排除标签链接
- java - Java从离散类和接口继承?
- iis - 是否可以从 WMI 获取所有 IIS 站点?
- mysql - 使用 Python 插入 SQL 数据库
- jquery - JQuery代码没有通过获取ID名称显示另一个链接列表onhover
- python - 文件夹未显示在我的本地目录中,但它在我的编辑器中
- swift - 在Swift中按升序对时间字符串(HH:mm)进行排序
- php - PHP函数返回false && true && false?