【发布时间】:2011-07-08 18:01:05
【问题描述】:
我正在尝试学习 STL 库,但遇到了一个奇怪的问题。这段代码编译完美:
void Show(vector<int> myvec)
{
vector<int>::iterator it;
cout << "Vector contains:";
for( it = myvec.begin(); it < myvec.end(); it++)
{
cout << " " << *it;
}
cout << endl;
}
虽然这个在编译时给了我一条错误消息:
template <class T>
void Show2(vector<T> myvec)
{
vector<T>::iterator it;
cout << "Vector contains:";
for( it = myvec.begin(); it < myvec.end(); it++)
{
cout << " " << *it;
}
cout << endl;
}
错误是:
$ g++ hello.cpp
hello.cpp: In function ‘void Show2(std::vector<T, std::allocator<_Tp1> >)’:
hello.cpp:19: error: expected ‘;’ before ‘it’
hello.cpp:21: error: ‘it’ was not declared in this scope
这似乎是一个非常简单的错误,但我找不到它。
【问题讨论】:
-
之前可能回答了很多,但如果您不知道此类术语存在,则很难搜索类型名称/依赖名称
-
@FredOverflow 这是一个非常好的链接,我现在可能会阅读它。但是,就像@Erik 所说,如果您不知道根本问题是什么,您将搜索许多特定术语,而不是更普遍的问题。我对迭代器、模板、向量、STL 进行了多次搜索……但一无所获,我什至不知道关键字
typename存在(:( 是的,我是菜鸟 :P)。我以为只是一个愚蠢的语法错误。 -
没关系,没有人抱怨 ;)
标签: c++ templates stl vector iterator