c++ - Iterating in a sorted manner over a std::vector<std::pair<T,U> > object -
i reading object database of type foo, defined below. object vector of foo members, foo members consists of string id , container object.
typedef std::pair<std::string, container> foomember; typedef std::vector<foomember> foo;
i wish iterate on foo object in sorted form, sorting done respect id. using following function create first sorted version of object. can see, object sorted in case insensitive manner. there better way me iterate on object compared how doing it?
foo sortedfoo(foo& value) const { foo returnvalue; returnvalue.reserve(value.size()); // use map sort items std::map<std::string, foomember> sortedmembers; { foo::iterator = value.begin(); foo::iterator end = value.end(); for(; i!=end; ++i) { std::string name = i->first; boost::algorithm::to_lower(name); sortedmembers[name] = *i; } } // convert map vector of values in sorted order std::map<std::string, foomember >::iterator = sortedmembers.begin(); std::map<std::string, foomember >::iterator end = sortedmembers.end(); for(; i!=end; ++i) { returnvalue.push_back(i->second); } return returnvalue; }
you can use std::sort
#include <algorithm> bool comparator(const foomember& i, const foomember& j) { std::string str1 = i.first; boost::algorithm::to_lower(str1); std::string str2 = j.first; boost::algorithm::to_lower(str2); return (str1 < str2); } void sortfoo(foo& value) { std::sort (value.begin(), value.end(), comparator); }
or, can keep foo
objects in std::map<std::string, foo>
beginning remain sorted.
Comments
Post a Comment