1

我想在某个模板函数中迭代一个容器。如果容器是双端队列但它存储的类型是未知的,我试过:

template <typename T>
void PrintDeque(deque<T> d)
{
    deque<T>::iterator it; //error here
    for(it=d.begin();it!=d.end();it++)
        cout<<*it<<" ";
    cout<<endl;
}

或者,如果我对未知容器尝试此操作:

template <typename T>
void PrintDeque(T d)
{
    T::iterator it;   //error here
    for(it=d.begin();it!=d.end();it++)
        cout<<*it<<" ";
    cout<<endl;
}

两者都给出编译错误。如何在模板函数中创建一个迭代器,以便我可以迭代容器?

4

3 回答 3

3
template <typename T>
void PrintDeque(T d)
{
    typename T::iterator it;   //error here
    for(it=d.begin();it!=d.end();it++)
        cout<<*it<<" ";
    cout<<endl;
}

您需要typename在它之前,因为编译器不知道您正在命名一个类型或一个静态变量。它被称为依赖类型。

http://pages.cs.wisc.edu/~driscoll/typename.html

顺便说一句,并对其他答案发表评论。有些编译器不需要这个,有些则需要。GCC 是需要此说明的编译器之一。

于 2013-11-18T18:07:04.790 回答
1
#include <deque>
#include <iostream>
using namespace std;

template<typename range>
void PrintEverythingIn(range C)
{
        for (auto e : C)
                cout << e << ' ';
        cout << endl;
}

deque<int> demo { 1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,20 };

int main() { PrintEverythingIn(demo); }
于 2013-11-18T19:19:55.547 回答
0

您可以使用以下代码:

template <typename T>
void PrintDeque(deque<T> d)
{
    deque<T>::iterator it;
    for(it=d.begin();it!=d.end();it++)
        cout<<*it<<" ";
    cout<<endl;
}

此代码在我的带有 vs12 的 Windows 上运行良好。


笔记:

template <typename T>
void PrintDeque(deque<T> d)
{
    deque<typename T>::iterator it; //error here
    for(it=d.begin();it!=d.end();it++)
        cout<<*it<<" ";
    cout<<endl;
}

这段代码,你发布的内容在我的电脑上也可以正常工作。

于 2013-11-18T18:08:16.733 回答