我有一个代码,我需要找到它的输出:
int main()
{
list<int> intList;
ostream_iterator<int> screen(cout, " ");
list<int>::iterator listIt;
intList.push_back(5);
intList.push_front(23);
intList.push_front(45);
intList.pop_back();
intList.push_back(35);
intList.push_front(0);
intList.push_back(50);
intList.push_front(34);
copy(intList.begin(), intList.end(), screen);
listIt = intList.begin();
intList.insert(listIt, 76);
++listIt;
++listIt;
intList.insert(listIt, 38);
intList.pop_back();
++listIt;
++listIt;
intList.erase(listIt);
intList.push_front(2 * intList.back());
intList.push_back(3 * intList.front());
copy(intList.begin(), intList.end(), screen);
cout << endl;
cout << endl;
}
我得到了这个输出:
34 0 45 23 35 50 46 76 34 0 38 45 23 138
当其他人得到:
34 0 45 23 5 0 35 50
70 76 34 0 38 45 23 0 35 210
哪一个是正确的,为什么?
答案 0 :(得分:2)
要对代码进行两次小的更改才能获得第二个输出:
#include <list>
#include <iostream>
#include <iterator>
using namespace std;
int main()
{
list<int> intList;
ostream_iterator<int> screen(cout, " ");
list<int>::iterator listIt;
intList.push_back(5);
intList.push_front(23);
intList.push_front(45);
intList.push_back(0); // 1. You had intList.pop_back();
intList.push_back(35);
intList.push_front(0);
intList.push_back(50);
intList.push_front(34);
copy(intList.begin(), intList.end(), screen);
cout << endl; // 2. Add an extra end-of-line
listIt = intList.begin();
intList.insert(listIt, 76);
++listIt;
++listIt;
intList.insert(listIt, 38);
intList.pop_back();
++listIt;
++listIt;
intList.erase(listIt);
intList.push_front(2 * intList.back());
intList.push_back(3 * intList.front());
copy(intList.begin(), intList.end(), screen);
cout << endl;
cout << endl;
}
输出:
34 0 45 23 5 0 35 50
70 76 34 0 38 45 23 0 35 210
我怀疑你们两个都没有运行完全相同的代码...