如何随机分配到C ++中的向量? [英] How to randomly assign to vector in C++?
问题描述
我是C ++的新手,并且不断被告知使用 std :: vector
而不是 new []
。
I am new to C++, and am continuously told to use std::vector
instead of new[]
.
我试图实现这个功能,在哪里我知道向量的大小,并要随机(不是顺序)分配。
I am trying to achieve this functionality, in where I know the size of the vector and want to assign to it randomly (not sequentially).
但是,当运行这个程序时,我的程序终止,没有错误输出,所以我很累。
However, when running this, my program terminates with no error output, so I am stumped.
vector<string> v1;
v1.resize(2);
v1.insert(v1.begin() + 1, "world");
v1.insert(v1.begin() + 0, "world");
cout << v1.at(1) << endl;
推荐答案
不要放弃, / p>
Don't give up, it's easier than that
vector<string> v1(2);
v1[1] = "world";
v1[0] = "world";
cout << v1[1] << endl;
vector :: insert
想要添加项目到你的向量,不是当你想要替换已经在那里, vector :: insert
改变矢量的大小换句话说,
vector::insert
is for when you want to add items to your vector, Not when you want to replace ones that are already there, vector::insert
changes the size of the vector in other words.
这篇关于如何随机分配到C ++中的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!