I get the Foo vector from the API as follows:
std::vector<Foo> foos;
Then I wrote a function called
std::vector<std::string> getKeys(const std::vector<Foo>&)
which iterates over the container and pulls out a key of type std :: string for each Foo object.
How would you iterate over Foo objects in foos in sorted order, where sorting is done by key and case insensitive. In addition, I would prefer not to make a sorted copy of foos, since it is large.
Here's my attempt, which works, but I wonder if this can be done better.
struct CaseInsensitiveComparitor { bool operator ()(const std::pair<std::string, Foo&> lhs, const std::pair<std::string, Foo&> rhs) const { std::string str1 = lhs.first; boost::algorithm::to_lower(str1); std::string str2 = rhs.first; boost::algorithm::to_lower(str2); return (str1 < str2); } }; // map key to Foo std::vector<std::pair<std::string, Foo*> > tempFoos; { std::vector<std::string> keys = getKeys(foos); std::vector<std::string>::iterator begin = keys.begin(); std::vector<std::string>::iterator i = keys.begin(); std::vector<std::string>::iterator end = keys.end(); for(;i!=end;++i) { tempFoos.push_back(*i, &foos[distance(begin,i)]); } std::sort(tempFoos.begin(), tempFoos.end(), CaseInsensitiveComparitor()); } std::vector<Foo*> sortedFoos; std::vector<std::pair<std::string, Foo*> >::iterator i = tempFoos.begin(); std::vector<std::pair<std::string, Foo*> >::iterator end = tempFoos.end(); for(;i!=end;++i) { sortedFoos.push_back(i->second); }
source share