1

lexicographical_compare()C++の関数を使用して文字列を並べ替える方法はありますか?

私はSTLソートでそれを行うことができますが、私の質問はlexicographical_compare()機能についてです.

4

2 に答える 2

6

std::lexicographical_compare文字列をソートする必要はありません。あなただけのstd::sortアルゴリズムが必要です:

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
  std::string s("qwertyuioplkjhgfdsazxcvbnm");
  std::cout << s << "\n";
  std::sort(s.begin(), s.end());
  std::cout << s << "\n";
}

文字列のコレクションのソートにも同じことが当てはまります。

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

int main()
{
  std::vector<std::string> v{"apple" , "Apple" ,"AppLe" , "APPLe"};
  for (const auto& s : v)
    std::cout << s << " ";
  std::cout << "\n";
  std::sort(v.begin(), v.end());
  for (const auto& s : v)
    std::cout << s << " ";
  std::cout << "\n";
}
于 2013-05-09T14:05:30.510 に答える
6

質問の言葉遣いが悪い。もちろん、std::lexicographical_compareは何も変更しないので、並べ替えるには を使用するだけでは不十分です。何らかの方法で (または同等のものを)std::lexicographical_compare使用する必要があります。「 s のstd::sortコンテナーを辞書式にソートする方法は?」に対する正しい答えは、on s が辞書式の比較であるためです。std::stringstd::sort(vec.begin(), vec.end())operator<std::string

あなたの質問が、コンテナの範囲を辞書順に並べ替える方法に関するより広範な質問の例であると仮定すると(これは、カスタム比較関数オブジェクトを使用しての動作を変更する方法に関する質問ですstd::sort)、あなたはただstd::sort比較演算子を提供します。例えば:

// A function objecto to do lexicographical comparisons
template <typename Container>
bool LexCompare(const Container& a, const Container& b) {
    return std::lexicographical_compare(a.begin(), a.end(),
                                        b.begin(), b.end());
}

// Use that comparison function to sort a range:
template <typename ContainerIterator>
void sort_by_lexicographical_comapre(ContainerIterator beg,
                                     ContainerIterator end)
{
    std::sort(beg, end, LexCompare<typename ContainerIterator::value_type>);
}


int main() {
    std::vector<std::string> v;
    v.push_back(std::string());
    v[0].push_back('1');
    v[0].push_back('3');
    v[0].push_back('0');
    v.push_back(std::string());
    v[1].push_back('1');
    v[1].push_back('3');
    sort_by_lexicographical_comapre(v.begin(), v.end());

    for (int i = 0; i != v.size(); ++i) {
        std::cout << v[i] << "\n";
    }
    return 0;
}

上記を変更しvて型を持ちstd::vector<std::vector<int> >、整数をそれらにプッシュバックしても、引き続き機能します。

于 2015-01-29T22:41:45.727 に答える