简体   繁体   English

关于模板函数中的矢量迭代器的问题

[英]Question about vector iterator in template functions

I'm trying to learn the STL library and I'm having a weird problem. 我正在尝试学习STL库,但遇到了一个奇怪的问题。 This code compiles perfectly: 这段代码可以完美地编译:

void Show(vector<int> myvec)
{
    vector<int>::iterator it;
    cout << "Vector contains:";
    for( it = myvec.begin(); it < myvec.end(); it++) 
    {
         cout << " " << *it;
    }
    cout << endl;
}

while this one gives me an error message at compile time: 虽然这在编译时给了我一条错误消息:

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;
}

The error is: 错误是:

$ 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

It seems a very simple mistake, but I couldn't find it. 这似乎是一个非常简单的错误,但我找不到。

You need to say typename vector<T>::iterator it . 您需要说出typename vector<T>::iterator it

On another note, you're passing vector s by value. 另一方面,您正在按值传递vector That means the entire vector gets copied in the function call. 这意味着整个vector将在函数调用中复制。 void Show(vector<T> const &myvec) and using const_iterator would be wiser. void Show(vector<T> const &myvec)并使用const_iterator会更明智。

You need this: 你需要这个:

typename vector<T>::iterator it;

This tells the compiler that vector<T>::iterator should be treated as a type, something it can't assume since iterator is dependent on what T is. 这告诉编译vector<T>::iterator应将vector<T>::iterator视为一种类型,由于iterator取决于T是什么,因此无法假定该类型。

Some compilers have problems detecting what is a member name and what is a type name, when inside templates. 在模板内部时,某些编译器在检测什么是成员名和什么是类型名时遇到问题。 Try writing something like this in the first line of your template function body. 尝试在模板函数主体的第一行中编写类似的内容。

typename vector<T>::iterator it;

Maybe it works using typename vector<T>::iterator it; 也许使用typename vector<T>::iterator it; Your compiler cannot know that there is an inner class iterator. 您的编译器无法知道有一个内部类迭代器。

In the first instance the parameter, although it uses a template, is not a template, it is a fully defined class ( vector<int> ) 在第一个实例中,参数尽管使用模板,但不是模板,而是完全定义的类( vector<int>

In the latter instance the parameter is a template on type T and thus requires typename 在后一种情况下,该参数是类型T上的模板,因此需要类型名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM