Mohamed Ahmed
Mohamed Ahmed

Reputation: 455

insert in C++ vector

I want to insert a bit from a bitset in the beginning of a vector. I am having a hard time understanding how to do that. Here is how I think I can do it:

keyRej.insert(x, inpSeq[0]);

I don't know what to put in the place of x?

Upvotes: 1

Views: 138

Answers (2)

juanchopanza
juanchopanza

Reputation: 227418

I don't know what to put in the place of x?

An iterator to the position you want to insert in:

keyRej.insert(keyRej.begin(), inpSeq[0]);

Semantically, the inserted element goes before the iterator passed as first argument. But this will result in all elements of the vector having to be moved across one position, and may also incur a re-allocation of the vector's internal data storage block. It also means that all iterators or references to the vector's elements are invalidated.

See this reference for std::vector::insert for more information.

Note that there are containers, such as std::deque, for which appending elements to the front is cheap, and reference (but not iterator) validity is maintained.

Upvotes: 5

galop1n
galop1n

Reputation: 8824

x is an iterator according to the documentation you probably read here, the new object is insert just before it.

keyRej.insert(keyRej.begin(), inpSeq[0]);

Upvotes: 3

Related Questions