【发布时间】:2015-01-16 13:19:23
【问题描述】:
我想对任意类型的向量进行排序,所以写了如下代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template<class T>
bool compare(T a, T b) {
return a < b;
}
int main() {
vector<int> v;
v.push_back(3);
v.push_back(4);
v.push_back(2);
v.push_back(1);
sort(v.begin(), v.end(), compare);
for (size_t i = 0; i < v.size(); i++) {
cout << v.at(i) << " ";
}
return 0;
}
此代码未编译,并显示如下错误消息:
..\src\Test.cpp:22:34: error: no matching function for call to 'sort(std::vector<int>::iterator, std::vector<int>::iterator, <unresolved overloaded function type>)'
..\src\Test.cpp:22:34: note: candidates are:
... and more
当我使用具体类型实现比较函数时,它可以工作。 谁能告诉我如何使用模板比较功能来做到这一点?
【问题讨论】:
标签: c++ sorting templates vector std