簡體   English   中英

帶模板的c ++迭代器

[英]c++ iterator with template

我有一個關於如何在模板方式下使用迭代器的問題。
這是我想要做的一個例子,問題是,在for循環中如何初始化迭代器pp?

我讀過類似的問題,但我不能完全理解,因為我是初學者。
迭代器類型應該在這個C ++模板中應該是什么?
任何人都可以幫助並提供一些簡單的解釋嗎?

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

我收到的錯誤消息:
'std :: vector :: 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;
}

來源: http//www.daniweb.com/software-development/cpp/threads/187603/template-function-vector-iterator-wont-compile

就像迪特說的那樣,新版本的gcc幾乎可以告訴你需要哪個typename:

error: need 'typename' before 'std::vector<T>::iterator' 
       because 'std::vector<T>' is a dependent scope

簡單修復:

for(typename std::vector<T>::iterator pp = input.begin(); 
          pp != input.end(); ++pp)

下面是對T :: iterator的解釋,其中模板參數T可能是vector <int>或list <int>

在合格的依賴類型之前,您需要typename。 如果沒有typename,則會有一個C ++解析規則,即除非導致語法錯誤,否則應將合格的從屬名稱解析為非類型。

有關更全面的解釋,請查看為什么關鍵字“typename”需要在合格的從屬名稱之前,而不是在合格的獨立名稱之前?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM