[英]c++ iterator with template
I have a problem about how to use iterator under the template manner. 我有一个关于如何在模板方式下使用迭代器的问题。
Here is an example I am trying to do, the problem is that, inside the for loop how can I initial the iterator pp ? 这是我想要做的一个例子,问题是,在for循环中如何初始化迭代器pp?
I have read a similar question, but I cannot fully understand that since I am a beginner. 我读过类似的问题,但我不能完全理解,因为我是初学者。
What should the iterator type be in this C++ template? 迭代器类型应该在这个C ++模板中应该是什么?
Can anyone help and also provide some simple explanation? 任何人都可以帮助并提供一些简单的解释吗?
#include <iostream>
#include <vector>
template <class T>
void my_print(std::vector<T> input){
for(std::vector<T>::iterator pp = input.begin(); pp != input.end(); ++pp)
std::cout << *pp << "\n";
}
int main(int argc,char* argv[]){
std::vector<int> aa(10,9);
my_print(aa);
return 0;
}
error message I got: 我收到的错误消息:
'std::vector::iterator' is parsed as a non-type, but instantiation yields a type 'std :: vector :: iterator'被解析为非类型,但实例化会产生一个类型
Add a typename
before the iterator
在iterator
之前添加一个typename
#include <iostream>
#include <vector>
template <class T>
void my_print(std::vector<T> input)
{
for (typename std::vector<T>::iterator pp = input.begin(); pp != input.end(); ++pp)
{
std::cout << *pp << "\n";
}
}
int main(int argc, char* argv[])
{
std::vector<int> aa(10, 9);
my_print(aa);
return 0;
}
source: http://www.daniweb.com/software-development/cpp/threads/187603/template-function-vector-iterator-wont-compile 来源: http : //www.daniweb.com/software-development/cpp/threads/187603/template-function-vector-iterator-wont-compile
Like Dieter says, newer versions of gcc will pretty much tell you where typename is needed: 就像迪特说的那样,新版本的gcc几乎可以告诉你需要哪个typename:
error: need 'typename' before 'std::vector<T>::iterator'
because 'std::vector<T>' is a dependent scope
Simple fix: 简单修复:
for(typename std::vector<T>::iterator pp = input.begin();
pp != input.end(); ++pp)
Here is an explanation Error with T::iterator, where template parameter T might be vector<int> or list<int> 下面是对T :: iterator的解释,其中模板参数T可能是vector <int>或list <int>
Before a qualified dependent type, you need typename. 在合格的依赖类型之前,您需要typename。 Without typename, there is a C++ parsing rule that says that qualified dependent names should be parsed as non-types even if it leads to a syntax error. 如果没有typename,则会有一个C ++解析规则,即除非导致语法错误,否则应将合格的从属名称解析为非类型。
For a more comprehensive explanation, check out Why is the keyword "typename" needed before qualified dependent names, and not before qualified independent names? 有关更全面的解释,请查看为什么关键字“typename”需要在合格的从属名称之前,而不是在合格的独立名称之前?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.