将构造函数的参数分配给向量变量
Assigning constructor's argument to the vector variable
我有这个代码:
class Entry
{
protected :
string itemName;
vector<string> allItems;
public :
Entry(string item) : allItems(item){};
}
我想使用push_back()
将构造函数参数添加到向量变量allItems
中。我该怎么做:
Entry("My Entry Name");
然后将变量My Entry Name添加到<vector>
考虑使用列表初始化:
Entry(string item) : allItems({ item }){};
在C++11中,您可以从初始值设定项列表构建:
Entry(std::string item) : allItems({std::move(item)}){};
在这种情况下,您也可以只使用C++98并使用填充构造函数,但只使用1个元素进行填充:
Entry(const std::string& item) : allItems(1, item){};
相关文章:
- 尝试通过多个向量访问变量时,向量下标超出范围
- 变量没有改变?通过向量的函数调用
- C++:如何读取分离变量,然后读取向量
- 在向量内更改变量的值不会改变其在向量外的值
- 将不同类型的变量添加到向量中
- C++:将向量传递到构造函数以创建成员变量的最佳方法?
- 从类指针的向量创建成员变量的向量
- 如何在C++中将字节向量(std::vector<uint8_t>)转换为不同的uint32_t,uint16_t和uint8_t变量
- 分配具有 2D 向量大小的变量的内存
- 如何访问基类向量中的子类变量?(对于实体组件系统)
- 在不同条件下无法访问我的向量变量
- 从类向量变量中获取值
- 全球向量变量上的外部不起作用
- 如何在C 中使用指针到向量变量
- 为什么编译器认为我没有为向量变量命名类型?
- 无法通过 gdb 将观察点设置为局部向量变量
- 将构造函数的参数分配给向量变量
- 在多个c++文件中共享向量变量
- 如何在c++中返回向量变量的元素个数
- 为什么<int>常量引用返回的向量变量不起作用