次のように、API から Foo のベクトルを受け取ります。
std::vector<Foo> foos;
次に、という関数を作成しました
std::vector<std::string> getKeys(const std::vector<Foo>&)
コンテナーを反復処理し、各 Foo オブジェクトの std::string 型のキーを取り出します。
foos の Foo オブジェクトをソートされた順序でどのように反復処理しますか。ソートはキーで大文字と小文字を区別しない方法で行われます。さらに、サイズが大きいため、foos のソートされたコピーを作成したくありません。
これが私の試みです。これは機能しますが、もっとうまくできるかどうか疑問に思っています。
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);
}