-1

How to insert something in a list using its iterator? for example, I have a list of objects myobj where myobj contains another list<int>.

class myobj {
    //other data goes here
    list<int> l;
};
list <myobj> x;

Suppose I want to call the insert() function for the list in the nth element of x, I'll do something like

list<myobj>::iterator itr = x.begin();
std::advance(itr,n);
itr->insert(n); //It gives a compilation error.

I tried to learn insert_iterator but most of the examples I got were used with copy() function but here I want to call the insert() function of the list inside myobj.

Yousuf Khan
  • 334
  • 3
  • 12

2 Answers2

0

There is no operator +=() defined for std::list iterators. To advance your iterator use std::advance.

http://en.cppreference.com/w/cpp/iterator/advance

auto iter = x.begin();
std::advance(iter,n);

Keep in mind that you want to be certain your list is large enough for the iteration you are trying to perform.

To access the contents:

iter->l.insert(n);

When using an iterator, the '.' operator returns methods held by the iterator. If you dereference the iterator, (*iter). or use the operator ->() You should get access to the methods held by the object in your list.

Mikel F
  • 3,567
  • 1
  • 21
  • 33
0

The call you want is l.insert(iter, value);

That inserts the object named value into the list l at the position pointed to by iter.

Marshall Clow
  • 15,972
  • 2
  • 29
  • 45