- I want to use
std::sort()
on astd::vector<std::string *>
. - For this, I want to overload
<
. - I guess the
std::sort()
function doesn't call my operator because the vector actually hasstd::string *
as type instead ofstd::string
. But I'm not sure how to specify this. - I would like to achieve this without using a third parameter in
std::sort()
#include <iostream>
#include <vector>
#include <algorithm>
bool operator<(std::string& str_1, std::string& str_2){
std::cout<<str_1[0] <<" < " << str_2[0] << std::endl;
return str_1[0] < str_2[0];
}
int main(int argc, const char * argv[]) {
std::string str1 = "abc";
std::string str2 = "def";
std::string str3 = "ghi";
std::string str4 = "bcd";
std::string str5 = "fgh";
//test the operator first
std::cout << (str1<str2) << std::endl;
std::vector<std::string *> str_vector;
str_vector.push_back(&str1);
str_vector.push_back(&str2);
str_vector.push_back(&str3);
str_vector.push_back(&str4);
str_vector.push_back(&str5);
std::sort(str_vector.begin(), str_vector.end());
for (std::vector<std::string *>::iterator it=str_vector.begin(); it!=str_vector.end(); ++it)
std::cout << ' ' << **it << std::endl;
return 0;
}
The operator seems to be well implemented, but is never called during std::sort()
This is the console output:
a < d
1
fgh
bcd
ghi
def
abc
Program ended with exit code: 0
THANKS!
Aucun commentaire:
Enregistrer un commentaire