Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 关于模板函数中向量迭代器的问题_C++_Templates_Stl_Vector_Iterator - Fatal编程技术网

C++ 关于模板函数中向量迭代器的问题

C++ 关于模板函数中向量迭代器的问题,c++,templates,stl,vector,iterator,C++,Templates,Stl,Vector,Iterator,我试图学习STL库,但我遇到了一个奇怪的问题。这段代码编译得非常完美: void Show(vector<int> myvec) { vector<int>::iterator it; cout << "Vector contains:"; for( it = myvec.begin(); it < myvec.end(); it++) { cout << " " << *it;

我试图学习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;
}
void显示(矢量myvec)
{
向量::迭代器;

cout某些编译器在检测模板中的成员名称和类型名称时遇到问题。请尝试在模板函数体的第一行中编写类似的内容


typename vector::iterator it;

您需要说
typename vector::iterator it


另一方面,您通过值传递
向量。这意味着整个
向量将在函数调用中被复制。
void Show(vector const&myvec)
和使用
const\u迭代器将更明智。

可能它使用
typename vector::iterator it;
编译器无法知道存在内部类迭代器。

您需要:

typename vector<T>::iterator it;
typename向量::迭代器;

这告诉编译器应该将
vector::iterator
视为一种类型,这是它不能假设的,因为
iterator
依赖于
t
是什么。

首先,参数虽然使用模板,但不是模板,它是一个完全定义的类(
vector


在后一种情况下,参数是类型T上的模板,因此需要typename

可能与以前回答过很多问题的名称重复,但如果您不知道这些术语exist@FredOverflow这是一个非常好的链接,我现在可能会读它。但是,就像@Erik说的,如果你不知道w这是根本的问题,你将搜索许多特定的术语,而不会搜索更一般的问题。我搜索了很多迭代器、模板、向量、STL……但没有发现任何我甚至不知道关键字
typename
存在的东西(:(是的,我是noob:P).我认为这只是一个愚蠢的语法错误。没关系,没人抱怨;)如果他通过const Ref,也需要告诉他使用一个conthyTrava.正确,但它不是一个编译器问题。C++标准规定编译器将模板中的依赖名当作成员而不是类型,除非使用了类型名。它不是“一些编译器”。语法根本不允许。“一些编译器”如果没有typename解析失败,则可以通过使用typename重试来双重猜测程序员,从而编译一些不正确的案例。
$ 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
typename vector<T>::iterator it;