views:

112

answers:

3

I want put a value from front of the list into an another list but I am getting an error.

for exmaple

List<int> li;
List<int> li2;

.............
.............

li2.push_back(li.front()); // this statement doesnt work for me. 

Can someone please help me.

example code:

   list<int> li;
   list<int> li2;
   li.push_back(1);
   li.push_back(2);
   li.push_back(3);

   for(int i=0;i<3;i++)
   {

    cout<<li.front()<<endl;
    li2.push_back(li.pop_front());

   }
+6  A: 

pop_front() just removes the first element from the list. It does not return the element.

You need to call front() to get the element at the beginning and then call pop_front() to remove it from the list:

li2.push_back(li.front());
li.pop_front();
James McNellis
yeah I got it. generally my pop returns my value. here in c++ it doesnt work
mousey
`std::list`'s `pop()` function *never* returns a value - the idea being that they didn't want the efficiency loss of a useless return when you don't want to use the return value. It's quite common - probably more common than not - for other sorts of linked list implementations to have their `pop()` return the value that you're popping, but `std::list` doesn't work that way.
Jonathan M Davis
@Jonathan M Davis: I think I read somewhere that the real reason that `pop()` doesn't return a value is that it is nearly impossible to write an exception-safe `pop()` that returns a value.
rlbond
+2  A: 

Also, Be aware that when the list is empty, the pop_front() and pop_back() will throw exceptions - resulting in segmentation fault. So it is mandatory to check the size of the list
i. directly - using the list function
ii.indirectly using the for loop as shown in the program.

Sample Code

#include <iostream>
#include <list>
using namespace std;


int main( int argc, char *argv[])
{

    list<int> li;
    li.pop_front();

    return 0;
}

Ouput

-laptop:~/Study/Pgm$ ./test
Segmentation fault

I think this is the behaviour in all OS, I use g++ (4.4.1) on Linux platform.

kumar_m_kiran
Calling `pop_front()` or `pop_back()` on an empty list does not result in an exception being thrown, it results in undefined behavior.
James McNellis
+2  A: 

Hmm...at least based on what you seem to be trying to accomplish, it looks like list.splice is probably the right tool for the job:

std::list<int> li, li2;

li.push_back(1);
li.push_back(2);
li.push_back(3);

li2.splice(li2.end(), li, li.rend(), li.rbegin());

In fact, splice is one of the few good reasons to use std::list at all.

Jerry Coffin