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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With