Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to randomly assign to vector in C++?

Tags:

c++

arrays

vector

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;
like image 855
Aly Avatar asked Nov 13 '12 19:11

Aly


2 Answers

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.

like image 148
john Avatar answered Sep 18 '22 18:09

john


First you resize it to have two empty strings:

{"", ""}

Then you insert "world" before begin() + 1 or the 2nd element:

{"", "world", ""}

Then you insert "world" before begin() or the 1st element:

{"world", "", "world, ""}

Then you access the 2nd element with v1.at(1) and get the empty string.

Presumably, you don't want std::vector::insert which inserts new elements between existing elements. You want to do this as you would with arrays, with operator[]:

vector<string> v1(2);
v1[1] = "world";
v1[0] = "world";
cout << v1.at(1) << endl;
like image 34
Joseph Mansfield Avatar answered Sep 22 '22 18:09

Joseph Mansfield