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.
相关文章