为什么我的代码不能正常工作?我忘记了 STL 列表中的某些内容吗?
Why is my code not working properly? Is there something in STL-list which I am forgetting?
这是我的代码:
#include <iostream>
#include <list>
using namespace std;
template <class T>
void display(list<T> l){
list<int>::iterator i;
for (i = l.begin(); i != l.end(); i++)
{
cout << *i << " ";
}
}
void enter(list<int> l){
list<int>::iterator i;
int index = 1;
for (i = l.begin(); i != l.end(); i++, index++)
{
// cout << "check" << endl;
cout << "Enter element at index " << index << endl;
cin >> *i;
}
}
int main(){
list<int> l;
display(l);
cout << endl;
l.push_front(1);
l.push_front(2);
l.push_front(3);
l.push_front(4);
l.push_front(5);
list<int> l2(3);
enter(l2);
display(l2);
cout << "EXE";
return 0;
}
下面程序的输出是:
Enter element at index 1
1
Enter element at index 2
2
Enter element at index 3
3
0 0 0 EXE
要求输出:
Enter element at index 1
1
Enter element at index 2
2
Enter element at index 3
3
1 2 3 EXE
问题是您在 enter
中按值传递列表。当您使用 cin >> *i
更新列表时,您更新的是 l2
的副本,而不是 main()
.
中声明的 l2
的副本
如果您想更新列表,则需要改为通过引用传递。
void enter(list<int>& l){
list<int>::iterator i;
int index = 1;
for (i = l.begin(); i != l.end(); i++, index++)
{
// cout << "check" << endl;
cout << "Enter element at index " << index << endl;
cin >> *i;
}
}
这是我的代码:
#include <iostream>
#include <list>
using namespace std;
template <class T>
void display(list<T> l){
list<int>::iterator i;
for (i = l.begin(); i != l.end(); i++)
{
cout << *i << " ";
}
}
void enter(list<int> l){
list<int>::iterator i;
int index = 1;
for (i = l.begin(); i != l.end(); i++, index++)
{
// cout << "check" << endl;
cout << "Enter element at index " << index << endl;
cin >> *i;
}
}
int main(){
list<int> l;
display(l);
cout << endl;
l.push_front(1);
l.push_front(2);
l.push_front(3);
l.push_front(4);
l.push_front(5);
list<int> l2(3);
enter(l2);
display(l2);
cout << "EXE";
return 0;
}
下面程序的输出是:
Enter element at index 1
1
Enter element at index 2
2
Enter element at index 3
3
0 0 0 EXE
要求输出:
Enter element at index 1
1
Enter element at index 2
2
Enter element at index 3
3
1 2 3 EXE
问题是您在 enter
中按值传递列表。当您使用 cin >> *i
更新列表时,您更新的是 l2
的副本,而不是 main()
.
l2
的副本
如果您想更新列表,则需要改为通过引用传递。
void enter(list<int>& l){
list<int>::iterator i;
int index = 1;
for (i = l.begin(); i != l.end(); i++, index++)
{
// cout << "check" << endl;
cout << "Enter element at index " << index << endl;
cin >> *i;
}
}