C++ 11 模板类和迭代器在G++中使用遇到的问题

255 阅读1分钟

C++ 模板类和迭代器

这段代码问题在哪里?

template <typename T> 
void print_arr_vector_const(const std::vector<T>& vec){
    cout<<"use for:"<<endl;  
    for (const auto& value:vec)
    {
     cout<< value<<" ";
    }

    cout<<endl;  
    cout<<"use iterator:"<<endl;  
    typename vector<T>::iterator itm = vec.begin();
    while (itm != vec.end())
    {
     cout<<*itm++<<" ";

    }
    
    cout<<endl;  

}

报错信息

PS F:\cc++\first> g++ catstr.cpp -o catstr
catstr.cpp: In function 'void print_arr_vector(const std::vector<T>&)':
catstr.cpp:106:5: error: need 'typename' before 'std::vector<T>::iterator' because 'std::vector<T>' is a dependent scope
  106 |     std::vector<T>::iterator itm = vec.begin();
      |     ^~~
catstr.cpp:106:29: error: expected ';' before 'itm'
  106 |     std::vector<T>::iterator itm = vec.begin();
      |                             ^~~~
      |                             ;
catstr.cpp:107:12: error: 'itm' was not declared in this scope; did you mean 'tm'?

原因:原因在于编译器无法识别std::vector<T>::iterator这个名称是一个成员变量还是一个类型

修改代码

template <typename T> 
void print_arr_vector_const(const std::vector<T>& vec){
    cout<<"use for:"<<endl;  
    for (const auto& value:vec)
    {
     cout<< value<<" ";
    }

    cout<<endl;  
    cout<<"use iterator:"<<endl;  
    typename vector<T>::iterator itm = vec.begin();
    while (itm != vec.end())
    {
     cout<<*itm++<<" ";

    }
    
    cout<<endl;  

}

还是报错,报错信息

PS F:\cc++\first> g++ catstr.cpp -o catstr
catstr.cpp: In instantiation of 'void print_arr_vector(const std::vector<T>&) [with T = int]':
catstr.cpp:200:22:   required from here
  200 |      print_arr_vector(vec);
      |      ~~~~~~~~~~~~~~~~^~~~~
catstr.cpp:106:49: error: conversion from '__normal_iterator<const int*,[...]>' to non-scalar type '__normal_iterator<int*,[...]>' requested

注意参数,const std::vector<T>& vecconst

解决方法(选其一):
  • 去掉参数const

  • typename vector<T>::**const_iterator** itm = vec.begin();