如何随机地分配在C ++中的向量? [英] How to randomly assign to vector in C++?

查看:169
本文介绍了如何随机地分配在C ++中的向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的C ++,和我不断告知使用的std ::矢量而不是新[]

我想实现这个功能,在我知道向量的大小和要随机(不按顺序)。

分配给它

然而,运行此时候,我的程序没有错误输出终止,所以我难住了。

 矢量<串GT; V1;
v1.resize(2);
v1.insert(v1.begin()+ 1,世界);
v1.insert(v1.begin()+ 0,世界);COUT<< v1.at(1) - ;&下; ENDL;


解决方案

不要放弃,这是比这更容易

 矢量<串GT; V1(2);
V1 [1] =世界;
V1 [0] =世界;COUT<< V1 [1];&下; ENDL;

向量::插入是当你想将项目添加到您的载体,而不是当你想替换那些已经存在,矢量::插入改变换句话说向量的大小

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;

解决方案

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 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆