【发布时间】: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?为什么我们可以省略&?
标签: c++ sorting stl c++20 std-ranges