Aneesh Narayanan
Aneesh Narayanan

Reputation: 3434

non-consecutive insertion in vectors

Is it possible to inset values in a std::vector in an non-consecutive manner like,

std::vector<int> Myvector;
//Myvector[0] = 123;
//Myvecotr[2] = 456;
//Myvector[5] = 789;

Upvotes: 0

Views: 365

Answers (3)

Carsten Greiner
Carsten Greiner

Reputation: 2938

When your code uses an index for an element that does not yet exist. Or in other words, if your index exceeds (>=) vector::size() then you are accessing a non existent element. Alas you end up in undefined-behaviour.

std::vector<int> Myvector;
Myvector[0] = 123; // boom  Myvector[0] was never created

So you need to add those elements

// the boring way
Myvector.push_back(0);
Myvector.push_back(0);
Myvector.push_back(0);
Myvector.push_back(0);
Myvector[0] = 123; // set element 0 to 123
Myvector[2] = 456; // set element 2 to 456

Or as stated in other answers you set the size (which I'd prefer):

Myvector.resize(5); 

Or state the size from begin on:

std::vector<int> Myvector(5); // 5 elements, all with the value of the default c'tor

Upvotes: 1

Raghuram
Raghuram

Reputation: 3967

If you can set the size in the beginning then you can do something like this

vector<int> iVec(5);
iVec[0] = 0;
iVec[2] = 2;
iVec[4] = 4;

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490108

Sort of. You can't really insert this way, but you can set the size, and only set values for those you care about.

If you really want it to be sparse (e.g., in your example Myvector[1], [3], [4] wouldn't exist at all), then no. For something like that, you could use an std::map<int, int> instead of a vector.

Upvotes: 6

Related Questions