我可以在不推送向量的情况下向向量添加值吗?
Can I add a value to a vector without pushing it?
有什么方法可以创建这样的向量对
吗 std::vector<std::pair<std::string, int>> myReg;
然后像这样添加它:
myReg[0].first = "title of the movie";
myReg[0].second = 1968;
myReg[1].first = "title of the 2nd movie";
myReg[1].second = 2008;
因为它给了我一个
调试断言失败
不使用这个:
myReg.push_back(std::pair<std::string, int>("title of the movie", 1968));
使用初始值设定项列表:
std::vector<std::pair<std::string, int>> myReg{
{"title of the movie", 1968},
{"title of the 2nd movie", 2008}
};
如果您稍后需要添加更多内容,它仍然很简单:
myReg.push_back({"title 3", 2000});
myReg.emplace_back("title 4", 2001);
对于您显示的确切代码片段,您必须首先执行以下操作myReg.resize(2)
:
std::vector<std::pair<std::string, int>> myReg;
myReg.resize(2);
myReg[0].first = "title of the movie";
您也可以将std::vector<...> myReg;
更改为myReg(2);
:
std::vector<std::pair<std::string, int>> myReg(2);
myReg[0].first = "title of the movie";
正如评论中提到的,另一种选择是使用std::map<>
而不是vector<>
;这给了你"自动扩展"(不调用push_back()
(,但通常不如vector<>
方便,因为内存不是连续的。 该代码看起来像
std::map<int, std::pair<std::string, int>> myReg;
myReg[0].first = "title of the movie";
你也可以用一个operator []
(和at()
(制作自己的类似向量的类来自动增长向量;这很快就会变得混乱,并且可能会被你的同事皱眉,但这里有一个(不一定推荐(的想法:
template<typename T>
class my_vector
{
std::vector<T> v;
public:
T& operator[](size_t i) {
if (i >= v.size())
v.resize(i+1);
return v[i];
}
// ... a lot of other methods copied from std::vector<> ...
};
my_vector<std::pair<std::string, int>> myReg;
myReg[0].first = "title of the movie";
您有 2 种常规方法:
首先,您可以使用 vector 的构造函数:
载体(initializer_list IL, const allocator_type& alloc = allocator_type(((;
std::vector<std::pair<std::string, int>> myReg(2);
myReg[0].first = "title of the movie";
myReg[0].second = 1968;
myReg[1].first = "title of the 2nd movie";
myReg[1].second = 2008;
显式向量 (size_type n, const value_type& val = value_type((, const allocator_type& alloc = allocator_type(((;
std::vector<std::pair<std::string, int>> myReg{
{"title of the movie", 1968},
{"title of the 2nd movie", 2008}
};
或者在启动前调整向量的大小:
std::vector<std::pair<std::string, int>> myReg;
myReg.resize(2)
myReg[0].first = "title of the movie";
myReg[0].second = 1968;
myReg[1].first = "title of the 2nd movie";
myReg[1].second = 2008;
感谢大家的帮助。很棒的人,有很多想法。
好的,这是从@Dan作为一个选项,尽管我正在研究可能使用类或@chris的方法
std::vector<std::pair<std::string, int>> myReg(1);
myReg[0].first = "title of the movie";
myReg[0].second = 1968;
myReg.resize(2);
myReg[1].first = "title of the 2nd movie";
myReg[1].second = 2008;
相关文章:
- 有没有办法向这个向量添加元素?
- 这种方式是否可以接受向向量添加unique_ptr?
- 向向量添加元素
- 无法向向量添加回调
- 如何将向量添加到结构中以创建一个库存系统,在该系统中,我可以仅使用一个结构向系统添加多种不同的葡萄酒
- 在一个类中向向量添加元素不适用于其他类
- 以下向 c++ 向量添加元素的方法有什么区别
- 我可以在不推送向量的情况下向向量添加值吗?
- 向向量C++添加对
- 使用单词键将多个行号的向量添加到我的地图中
- 在C++中向指针数组中的向量添加元素
- 要创建一个一开始没有特定维度的类Vector,请在类中创建一个方法,允许向向量添加维度
- 一次向 C++ 向量添加多个元素
- STL - 向存储在 STL 映射中的向量添加值
- 向向量添加向量
- 如何向结构类型的向量添加点
- 为什么我的课'当我向向量添加实例时,会调用s析构函数
- 向c++向量添加新字段
- 在c++中向向量添加对象vs向向量添加指针
- 当Type为unique_ptr时,为向量添加运算符[]