我想使用c ++ stl列表并使用迭代器来打印所有元素。这是代码:
#include<list>
#include<algorithm>
#include<string>
using namespace std;
int main(int argc, char* argv[]){
list<string> list;
//list<double> list_double(6);
//list<int> list_int(6, 0);
//list<double> list_double2(6, 0,0);
//list<int> else_list(list_int);
//list<double> iter(list_double.begin(), list_double.end());
list.push_front("1 jack");
list.push_front("2 jackson");
list.push_front("3 sally");
list<string>::iterator itrr;
for (itrr = list.begin(); itrr!= list.end(); itrr++){
string temp = *itrr;
print(temp)nt main(int argc, char* argv[]){
list<string> list;
//list<double> list_double(6);
//list<int> list_int(6, 0);
//list<double> list_double2(6, 0,0);
//list<int> else_list(list_int);
//list<double> iter(list_double.begin(), list_double.end());
list.push_front("1 jack");
list.push_front("2 jackson");
list.push_front("3 sally");
list<string>::iterator itrr;
for (itrr = list.begin(); itrr!= list.end(); itrr++){
string temp = *itrr;
print(temp);
}
return 0;
}
}
return 0;
}
当我尝试编译它时,它显示了一些错误:
list.cpp:17:7: error: unexpected type name 'string': expected expression
list<string>::iterator itrr;
^
list.cpp:17:16: error: cannot refer to class template 'iterator' without a template argument list
list<string>::iterator itrr;
~~^
/Library/Developer/CommandLineTools/usr/include/c++/v1/iterator:522:29: note: template is declared here
struct _LIBCPP_TEMPLATE_VIS iterator
^
list.cpp:18:7: error: use of undeclared identifier 'itrr'
for (itrr = list.begin(); itrr!= list.end(); itrr++){
^
list.cpp:18:28: error: use of undeclared identifier 'itrr'
for (itrr = list.begin(); itrr!= list.end(); itrr++){
^
list.cpp:18:47: error: use of undeclared identifier 'itrr'
for (itrr = list.begin(); itrr!= list.end(); itrr++){
^
list.cpp:19:18: error: use of undeclared identifier 'itrr'
string temp = *itrr;
^
那怎么了?谢谢!
答案 0 :(得分:2)
list<string> list;
将标识符list
定义为类型list<string>
的变量。这将标识符list
的先前定义替换为标准库std::list
类。这意味着当编译器在代码的许多后续点到达list<string>
时,list<string>
毫无意义。 <string>
与您对变量所做的任何操作都不匹配。
请谨慎使用标识符。制作名为list
的{{1}}会使读者和编译器感到困惑,因此请不要这样做。给变量起一个不同的名字。它到处都是名字,为什么不list
此问题与namelist?
的危险有关。有关更多信息,请阅读Why is "using namespace std" considered bad practice?