insert() function of containers

The book Essential C++ says:
iterator insert(iterator position) inserts an element before position.
The element is initialized to the default value of its type.

I tried this function, but it can't compile. Other overloaded versions do not have problem. Does this version of insert() not be supported only in this compiler or all compilers?
I use codeblocks 17.12 gcc 5.1.0 Windows/unicode - 32 bit.
Last edited on
I don't think that inset() is available for all containers. Check the reference.
Since people can't read his mind, OP needs to post a program showing how he was trying to use it so we can see what he did wrong.
Last edited on
insert() requires a second argument, the value of the element to be inserted.

We can use emplace() to insert a default initialised value.
https://en.cppreference.com/w/cpp/container/vector/emplace

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<int> vec { 1, 2, 3, 4, 5, 6, 7, 8, 9 } ;
    const auto print = [&vec] { for( auto v : vec ) std::cout << v << ' ' ; std::cout << '\n' ; };

    print() ; // 1 2 3 4 5 6 7 8 9

    auto iter = std::find( vec.begin(), vec.end(), 6 ) ;
    vec.emplace(iter) ;
    print() ; // 1 2 3 4 5 0 6 7 8 9

    iter = std::find( vec.begin(), vec.end(), -3 ) ;
    vec.emplace(iter) ;
    print() ; // 1 2 3 4 5 0 6 7 8 9 0
}

http://coliru.stacked-crooked.com/a/2e9c6c83123d6f12
Essential C++ didn't give the example of iterator insert(iterator position) . His examples for other versions of insert() are using list, so I use list to test it.
He gives four versions of insert(), and three of them works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
#include<list>
using namespace std;
int main()
{
    int testint[]={3, 5, 8, 14, 24, 28, 44, 67, 89, 92};
    list<int> listint(testint, testint+10);

    listint.insert(listint.begin(), 101); //insert one element
    listint.insert(listint.begin(), 3, 102); //insert three elements of 102
    listint.insert(listint.begin(), testint+2, testint+5); //insert by a pair of iterator

    listint.insert(listint.begin()); //insert with default value (can't work)
    //compiler gives an error that is no matching function
    list<int>::iterator iter=listint.begin();
    for(; iter!=listint.end(); ++iter)cout<<*iter<<" ";
}


The error is the same when I use vector.
So I wonder this iterator insert(iterator position) have never been supported or was supported before? Is the book right?
@JLBorges
I got it. So I can use emplace() to play this role.
Topic archived. No new replies allowed.