【问题标题】:Is the code for sorting a std::vector<std::string> by length correct in C++20?在 C++20 中按长度对 std::vector<std::string> 进行排序的代码是否正确?
【发布时间】:2020-06-20 05:23:54
【问题描述】:

我编写了一个按长度对向量字符串进行排序的代码。不幸的是,我不确定它是否会以这种形式在下一个标准中起作用。这是 C++20 中的正确代码吗?

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

int main() {
    std::vector<std::string> words = {"std", "vector", "string", "optional", "clamp"};

    // C++11
    // std::sort(words.begin(), words.end(), 
    //     [](auto& lhs, auto& rhs) { return lhs.length() < rhs.length(); });

    // maybe C++20?
    using namespace std::ranges;
    sort(words, {}, size); // or 'sort(words, less{}, size);'

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

【问题讨论】:

  • C++11 版本将继续工作。它们显然不会破坏所有曾经编写过的 C++ 代码。
  • 出于好奇 - 为什么size 参数被推断为任何相关的东西?推断为std::string::size 还是std::ranges::size?为什么我们可以省略&amp;

标签: c++ sorting stl c++20 std-ranges


【解决方案1】:

您的代码很好,可以在即将推出的 GCC 10 下编译。

正如@Ayxan 指出的那样,C++20 仍将具有通常的算法,因此如果您不想更改代码,则无需更改。

【讨论】:

    【解决方案2】:

    如果您有一些代码仅使用标准或非常常用的库,您可以尝试在以下网站上使用更新的编译器和实验性标准版本对其进行编译:

    和其他人。

    【讨论】:

      猜你喜欢
      • 2011-06-04
      • 1970-01-01
      • 2010-09-19
      • 1970-01-01
      • 2020-09-07
      • 2011-10-29
      • 1970-01-01
      • 2010-10-15
      • 1970-01-01
      相关资源
      最近更新 更多