在一些std
库template
的参数,一个需要定义他/她自己的功能比较less(a, b)
,more(a, b)
然后std::some_template<T, *, myComparator()>
,但是为什么呢?为什么我们仍然需要我们自己定义的功能比较
0
A
回答
5
比较器的目的是允许排序的stl容器中的对象排序。如果默认的比较器不适合容器所容纳的对象类型,则只需要提供自己的比较器。
例如,如果您要制作以下struct
的std :: set,那么您需要编写自己的比较器。
struct Person
{
std::string first_name, last_name, phone_number;
}
默认比较器知道如何比较数字和字符串,但它不知道如何比较Person对象。这是如何编写自定义比较器来按last_name排序Person对象的。
struct Person_Comparator
{
bool operator()(const Person &a, const Person &b) const {
return a.last_name < b.last_name;
}
};
1
又如让让一组具有一些不同的标准
int main()
{
//By default set will use std::less<int>()
//Lets make a set based on no. of 1's in binary representation of elements
set<int,mycomp> s;
for(auto i=1;i<20;i++) //Note :Duplicates 1's representation will be discarded
s.insert(i);
for(auto i:s)
cout<<i<< " "; //19 15 8 7 3 1
return 0;
}
以及相应的比较会像下面:
struct mycomp
{
bool operator()(const int& a, const int& b) const {
auto count_bits = [](long n){
unsigned int c;
for (c = 0; n; c++)
n &= n - 1;
return c;
};
return count_bits(a) != count_bits(b);
}
};
0
我们仍然偶尔也需要我们自己定义的函数比较器在泛型编程中,但我们并不总是需要自己编写:)你可以使用这个在线向导[http://www.xochellis.org/genericdataordering/wizard .php],以创建严格的弱命令函子,或者你需要的lambda。
例如,在上一个答案的示例Person_Comparator
中,您只需填写向导窗体中的三个字段,如this picture所示。
欲了解更多详细信息,您可以参考here还有:
最好的问候, 吉姆Xochellis
相关问题
- 1. PHP:为什么我们需要字符串比较功能?
- 2. 为什么我们需要crossCheckMatching功能?
- 3. 虽然我们有Swing,但为什么我们需要JavaFX?
- 4. 为什么我们自己需要合并几何?
- 5. DavLockDB:我们需要什么?
- 6. 为什么我们需要.htaccess的worpdress?
- 7. in solrImportScheduler为什么我们需要为delta导入定义reBuildIndexBeginTime?
- 8. 为什么我们不能创建我们自己的ostream对象
- 9. 什么是仿函数,为什么我们需要它们?
- 10. 什么是EJB回调,为什么我们需要它们?
- 11. 装配需要什么?为什么我们使用它们?
- 12. 为什么我们需要analysis_export当我们有analysis_port
- 13. 当我们有点子时,为什么我们需要Anaconda?
- 14. 为什么我们需要simple_one_for_one?
- 15. 为什么我们需要TensorFlow tf.Graph?
- 16. 为什么我们需要使用prompt.start()?
- 17. 为什么我们需要scalaz.stream迭代?
- 18. 为什么我们需要WCF
- 19. 为什么我们需要Anaconda 2.7?
- 20. 为什么我们需要编写log.isDebugEnabled?
- 21. 为什么我们需要ng-click?
- 22. 为什么我们需要Control.Lens.Reified?
- 23. 我们为什么需要纤维
- 24. 为什么我们需要org.junit.ComparisonFailure?
- 25. 为什么我们需要addRequestHeader方法?
- 26. 为什么我们需要时代?
- 27. 为什么我们需要ContinueWith方法?
- 28. 为什么我们需要Java NIO Selector?
- 29. 为什么我们需要使用ExitWindowsEx
- 30. 为什么我们需要包装类
什么是 “STL”? – 2013-07-27 14:17:45
所有的大多数都有它们的默认比较器。 它全部在程序员的意图 – P0W
@ H2CO3我不知道该给这个词打什么电话,这就是为什么我只是称它为stl,对不起 – mr5