I needed to store various strings in a map but I wanted to keep them ordered by size.
using a predicate like this:
struct strsize_less {
bool operator()(const string& l, const string& r) {
return l.size() < r.size();
};
};
would accomplish the ordering but it would discard the strings with the same size
int main() {
typedef map<string, int, strsize_less> mymap_t;
mymap_t mymap;
mymap["j" ] = 0;
mymap["i" ] = 1;
mymap["hh" ] = 2;
mymap["gg" ] = 3;
mymap["fff" ] = 4;
mymap["eee" ] = 5;
mymap["dddd" ] = 6;
mymap["cccc" ] = 7;
mymap["bbbbb"] = 8;
mymap["aaaaa"] = 9;
for( mymap_t::iterator i = mymap.begin(); i!=mymap.end(); ++i )
cout << "k = " << i->first << " - > v= " << i->second << endl;
return 0;
}
the output is:
k = j - > v= 1
k = hh - > v= 3
k = fff - > v= 5
k = dddd - > v= 7
k = bbbbb - > v= 9
My question: Is there any predicate I can use to achieve the following output:
k = j - > v= 0
k = i - > v= 1
k = hh - > v= 2
k = gg - > v= 3
k = fff - > v= 4
k = eee - > v= 5
k = dddd - > v= 6
k = cccc - > v= 7
k = bbbbb - > v= 8
k = aaaaa - > v= 9
Compare both the size and the string in the comparer:
Or, using C++11’s
std::tie: