Insert object at index of vector c++

The straight forward answer is you need an iterator. The iterator for std::vector supports random access, which means you can add or subtract an integer value to or from an iterator.

people.insert(people.begin() + index, temp);

The better answer is don’t use an index, use an iterator. What is your loop? You should be able to refactor the loop to use an iterator instead of an index.

Leave a Comment