Grapes
Grapes

Reputation: 2563

Shifting values of a vector in C++

Assuming the following basic vector:

 std::vector<int> numbers;
 numbers.push_back(0);
 numbers.push_back(1);
 numbers.push_back(2);
 numbers.push_back(3);

What is an efficient way to insert 6 new numbers in between 0 and 1?

Here is my approach right now, but I feel like it's not very efficient:

 for (int new_number=0;new_number<6;new_number++) {
     numbers.emplace(numbers.begin()+1+new_number,new_number);
 }

The reason I don't like this approach is that numbers 1-3 have to be moved 6 times. Is there a way to move these numbers just once instead of doing it 6 times? Then I can use this loop:

 for (int new_number=0;new_number<6;new_number++) {
     numbers[new_number+1]=new_number;
 }

Here is what I am trying to accomplish:

Vector Before Shifting:

0 1 2 3

Vector After Shifting:

0 X X X X X X 1 2 3

Upvotes: 5

Views: 26537

Answers (3)

Kerrek SB
Kerrek SB

Reputation: 476920

If you must insert items one-by-one from disparate sources, so you can't use the range-insertion, one option is to insert everything at the back, and then use std::rotate:

#include <algorithm>

v.reserve(v.size() + 6);

v.push_back(12);
v.push_back(foo());
// ...

std::rotate(v.begin() + 1, v.begin() + 4, v.end());

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

There is an overload of the insert function that lets you insert n identical items:

// Add six copies of -1 to the vector starting at position 1
numbers.insert(numbers.begin()+1, 6, -1);

You can use another overload that takes three iterators - the iterator where to insert, and a begin/end pair of iterators from where to take the data:

// Insert addedNUmbers at position 1
numbers.insert(numbers.begin()+1, addedNUmbers.begin(), addedNUmbers.end());

Upvotes: 10

Mats Petersson
Mats Petersson

Reputation: 129314

Something like this will insert 6 at the beginning of numbers:

numbers.insert(numbers.begin(), 6);

If you want to insert the number 6 after the number one:

numbers.insert(find(numbers.begin(), numbers.end(), 1), 6);

(Obviously, if you don't KNOW for sure that the number is in the list, you may want to check that before you insert!)

Upvotes: 0

Related Questions