【问题标题】:How to change the default string comparison?如何更改默认字符串比较?
【发布时间】:2020-07-07 02:24:03
【问题描述】:

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

  • 从字长取模值 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

【问题讨论】:

  • 大多数实现使用 ASCII 兼容的代码页,这意味着英文大写字母在小写字母之前。您可以在排序之前将大写转换为小写并反转,也可以编写自己的比较函数。
  • 在 ASCII 码中,std::string 的字典排序以数字、大写、小写而不是数字、小写、大写的形式工作。如果需要,您必须为 std::string 创建自己的比较函数并在 lambda 中调用它。
  • 写一个自定义字符串比较器?我怀疑,if 即将出现在你的兰巴车上。
  • % 3 的作用是什么?

标签: c++ sorting stl c++14 string-comparison


【解决方案1】:

我想你想要一个字符串比较函数:

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

bool
my_strless(std::string const& lhs, std::string const& rhs) noexcept
{
  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";
  }
}

【讨论】:

    猜你喜欢
    • 2021-07-02
    • 2011-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多