c++ - 迭代器的类型 C++

标签 c++ vector iterator

<分区>

我正在尝试编写自己的排序函数来对 vector 容器进行排序。

我希望以下面的方式调用它:

这个:排序(arr.begin(),arr.end() - 1)

arr.end() - 1 - 因为 arr.end() 返回下一个元素,实际上不是元素,返回迭代器结束

所以我想在任何类型上用迭代器调用我的函数。我试着运行这段代码:

#include<iostream>
#include<vector> 
using namespace std;

template<typename T1> 
void func(vector<T1>::iterator it) {
    cout << "\n" << *it; 
}

int main() {
    vector<int> arr(10);

    for(int i = 0;i < 10;++i)
        arr[i] = i+1;

    func<int>(arr.begin()); 
}

但是编译器说:

main.cpp:10:23: error: variable or field ‘func’ declared void  void func(vector<T1>::iterator it)
                              main.cpp:10:32: error: expected ‘)’ before ‘it’  void func(vector<T1>::iterator it)
                                 main.cpp: In function ‘int main()’: main.cpp:26:5: error: ‘func’ was not declared in this scope
     func<int>(arr.begin());
     func main.cpp:26:10: error: expected primary-expression before ‘int’
     func<int>(arr.begin());

请解释我的错误。谢谢

最佳答案

编译器不知道迭代器是 vector<T1> 中的类型

template<typename T1> void func(typename vector<T1>::iterator it) {
    cout << "\n" << *it; }

Inside a template, some constructs have semantics which may differ from one instantiation to another. Such a construct depends on the template parameters.

你应该写typename对于此类依赖类型。

关于c++ - 迭代器的类型 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48167251/

相关文章:

c++ - 是否可以卡住和转储程序状态?

c++ - 在 C++ 中实现进度可视化

c++ - 数组与 vector : Introductory Similarities and Differences

javascript - 三点之间的 Angular 数学解释

c++ - 如何在 std::set 中选择随机元素?

java - 迭代器和列表迭代器的区别?

c++ - 在方法中迭代 vector

c++ - visual studio 和 gcc 的 const 引用语法区别

c++ - 超时后检查服务器是否收到数据

c++ - 如何将 auto_ptr 添加到 vector