首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

the difference of push_back() and push_front() of sequence container list,该怎么解决

2013-01-28 
the difference of push_back() and push_front() of sequence container list想要得到的结果是 0 1 2 33

the difference of push_back() and push_front() of sequence container list
想要得到的结果是 
0 1 2 3
3 2 1 0

可是? ... 看代码


求解释。  iterator list push_back() push_front() c++
[解决办法]
# include <iostream>
# include <list>
using namespace std;

int main()
{
int a[4] = {0, 1, 2, 3};

list< int > int_list;
for(int i = 0; i<4; i++){
int_list.push_back(a[i]);
}
list< int >::iterator iter = int_list.begin();
list< int >::iterator iter_end = int_list.end();
for(; iter != iter_end; ++iter)
cout<< *iter <<" ";
cout<<endl;

int_list.clear();

int b[4] = {0, 1, 2, 3};
for(int i = 0; i<4; i++)
int_list.push_front(b[i]);

iter = int_list.begin();
iter_end = int_list.end();

for(; iter != iter_end; ++iter)
cout<< *iter <<" ";
cout<<endl; 
getchar();
return 0;
}


这样就对了,你先要清空啊,你没清空又往里面加了,肯定不对了。
[解决办法]
    iter = int_list.begin();
    iter_end = int_list.end();
 
    int b[4] = {0, 1, 2, 3};
    for(i = 0; i<4; i++)
        int_list.push_front(b[i]);

你的代码意思是:int_list里面本来有0,1,2,3,你又往里面加了3,2,1,0,最后int_list的
数据为:3 2 1 0 0 1 2 3。而你又在push_front前输入了iter = int_list.begin();
 iter_end = int_list.end(); 因此iter没有指在新的int_list的开始位,而是指在push_front前int_list数据的第一位,因此这样输出当然是0 1 2 3。

热点排行