Ross Allen
Ross Allen

Reputation: 473

c++: Returning iterator from vector::insert

I'm trying to insert the elements of a vector (s1) into a different vector (s2), at a specified point. As an example, this is achieved with the program

#include <vector>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    vector<string> s1;
    s1.push_back("Hi");
    s1.push_back("there!");

    vector<string> s2;
    s2.push_back("How");
    s2.push_back("are");
    s2.push_back("you?");

    vector<string>::iterator it = s2.begin();
    s2.insert(it, s1.begin(), s1.end());

    return 0;
}

However, if I want the insert command to return the iterator of the first inserted element, I was under the impression this command should work

it = s2.insert(it, s1.begin(), s1.end());

however I receive the compilation error

vector_insert.cc:20:8: error: no match for ‘operator=’ (operand types are ‘std::vector<std::__cxx11::basic_string<char> >::iterator {aka __gnu_cxx::__normal_iterator<std::__cxx11::basic_string<char>*, std::vector<std::__cxx11::basic_string<char> > >}’ and ‘void’)
 it = s2.insert(it, s1.begin(), s1.end());

Why does the compiler think insert has a void return when this page indicates an iterator return (http://en.cppreference.com/w/cpp/container/vector/insert). Note that this example is trivial because I could get the iterator to the initial inserted element with

it = s2.begin();

but this would not be true in general

Upvotes: 1

Views: 335

Answers (1)

Ross Allen
Ross Allen

Reputation: 473

The act of writing my question helped me find the answer (as usual). Figured I would leave the question for posterity and give the answer immediately.

The clue was right there in the cppreference page (duh). The void implementation of the insert function existed until C++11; the iterator implementation since C++11. Therefore the issue was only with my compiler. To fix, I just compiled with the -std=c++11 flag:

g++ -std=c++11 -o vector_insert vector_insert.cc

Upvotes: 1

Related Questions