C++ template won#39;t accept iterators(C++ 模板不接受迭代器)
问题描述
我正在重新学习 C++,并开始尝试应该是一个简单的算法:快速排序.我的函数有这个签名:
I'm re-learning C++, and have started by trying what should be a simple algorithm: QuickSort. My function has this signature:
template <class T>
void QSort(typename std::vector<T>::iterator begin, typename std::vector<T>::iterator end)
它在我的主函数中被调用:
And it is called in my main function:
int main()
{
std::vector<int> unsort({56,32,11,45,67,81,12,5});
std::vector<int>::iterator b=unsort.begin();
std::vector<int>::iterator e=unsort.end();
QSort(b, e);
return 0;
}
并给出此错误:
C:UsersDeusProjectsQSortmain.cpp||In function 'int main()':|
C:UsersDeusProjectsQSortmain.cpp|49|error: no matching function for call to 'QSort(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&, __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&)'|
||=== Build finished: 1 errors, 0 warnings ===|
编译器似乎无法解析 T 应该是什么.有没有办法做我想做的事情,或者我应该将参数声明为 T 类型,并处理由此产生的不确定性?
It seems that the compiler is having trouble resolving what T should be. Is there a way to do what I'm trying to do, or should I just declare the arguments as type T, and work with the resulting uncertainty?
推荐答案
编译器无法从你的函数调用中推断出 T
.想想当 std::vector<T>::iterator
是 T*
:
The compiler has no way to deduce T
from your function call. Think about what happens when std::vector<T>::iterator
is T*
:
int *b = ...;
int *e = ...;
QSort(b, e);
一般来说,如果你写typenameSomething
,那么TemplateParemter
在调用中是无法推导出来的.必须明确提供
In general, if you write typename Something<TemplateParameter>::anotherThing
, then the TemplateParemter
cannot be deduced in the call. It must be explicitly provided
QSort<int>(b, e);
我建议只使用 T
作为参数类型.这将使您不仅可以接受向量迭代器,还可以接受 T*
或 std::deque<T>::iterator
和任何其他随机访问迭代器.
I recommend to just use T
as the parameter type. That will allow you to not only accept vector iterators, but also T*
, or std::deque<T>::iterator
and any other random access iterators.
这篇关于C++ 模板不接受迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 模板不接受迭代器
基础教程推荐
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01