开发者

c++ lists question

开发者 https://www.devze.com 2022-12-29 05:28 出处:网络
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;

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());

   }


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();


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消