如何更改默认字符串比较?

问题描述 投票:0回答:1

如何按此特定顺序对字符串向量进行排序:

  • 字长取模数3

  • 字符串的字典比较(第一位数字,下,上)

我的代码:

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

int main() {
    std::vector<std::string> words = {
        "cat1",
        "cata",
        "cataaaa",
        "cataAaa",
        "catD",
        "dogdog",
        "dog"
    };

    std::sort(words.begin(), words.end(), [&](auto const& lhs, auto const& rhs) {
        return std::make_tuple(lhs.length() % 3, lhs)
             < std::make_tuple(rhs.length() % 3, rhs);
    });

    for (auto& word : words) {
        std::cout << word << "\n";
    }
}

输出:

dog
dogdog
cat1
catD
cata
cataAaa
cataaaa

我想要的是:

dog
dogdog
cat1
cata
catD
cataaaa
cataAaa
c++ sorting stl c++14 string-comparison
1个回答
2
投票

我认为您想要一个字符串比较器功能:

#include <cctype>
#include <iostream>
#include <string>
#include <vector>

bool
my_strless(std::string const& lhs, std::string const& rhs)
{
  auto const sz1 = lhs.size(), sz2 = rhs.size();

  // Length is closer to to 3
  if (sz1 % 3 < sz2 % 3)
    return true;
  if (sz2 % 3 < sz1 % 3)
    return false;

  // Generally shorter
  if (sz1 < sz2)
    return true;
  if (sz2 < sz1)
    return false;

  // Lexicographically smaller
  for (std::string::size_type i = 0; i != sz1; ++i) {
    auto const ch1 = std::tolower(static_cast<unsigned char>(lhs[i]));
    auto const ch2 = std::tolower(static_cast<unsigned char>(rhs[i]));
    if (ch1 < ch2)
      return true;
    if (ch2 < ch1)
      return false;
  }

  // Equal
  return false;
}

int
main()
{
  std::vector<std::string> words{ "cat1", "cata",   "cataaaa", "cataAaa",
                                  "catD", "dogdog", "dog" };

  std::sort(words.begin(), words.end(), my_strless);

  for (auto& word : words) {
    std::cout << word << "\n";
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.