gpt4 book ai didi

c++ - C++20 范围是否支持按功能分组?

转载 作者:行者123 更新时间:2023-12-03 06:54:31 25 4
gpt4 key购买 nike

有时,根据其中一个成员函数(getter 或某些计算)的值对对象进行分组/分区非常有用。

C++20 范围是否启用类似的东西

std::vector<Person> {{.Age=23, .Name = "Alice"}, {.Age=25, .Name = "Bob"}, {.Age=23, .Name = "Chad"}};
// group by .Age and put into std::map
std::map<int/*Age is int*/, std::vector<Person>> AgeToPerson = ...;
// 23 -> Person{23,Alice}, Person{23,Chad}
// 25 -> Person{25,Bob}

注1:有这个旧的question接受的答案是只使用原始 for 循环

注意 2:range-v3 有这个令人困惑的 group_by 算法,它似乎对我的任务毫无用处:

Given a source range and a binary predicate, return a range of ranges where each range contains contiguous elements from the sourcerange such that the following condition holds: for each element in therange apart from the first, when that element and the first elementare passed to the binary predicate, the result is true. In essence,views::group_by groups contiguous elements together with a binarypredicate.

最佳答案

在名称分组依据下,语言实际上提供了三种不同的功能:

  1. 采用二元谓词 ((T, T) -> bool) 并将该谓词计算为真的连续元素分组(例如 Haskell、Elixir、D、range-v3 类)
  2. 采用一元函数 ( T -> U ) 并将具有相同“键”的连续元素分组,并产生一系列 U, [T] 对(例如 Rust、Python,还有 D、F#)
  3. 采用一元函数 ( T -> U ) 并返回映射 U: [T] 的字典(例如 Clojure、Kotlin、Scala)。

前两个需要连续 元素 - 这意味着您需要按键排序。最后一个没有,因为无论如何你都在生产一个容器。您也可以从第二个版本生成第三个版本,即使没有排序,尽管这仍然需要一个循环

但如前所述,range-v3 仅提供第一个,而那个甚至不在 C++20 中。所以你需要写你自己的东西。在这种情况下,循环可能是最好的:

template <range R, indirectly_unary_invocable<iterator_t<R>> F>
/* other requirements such that you can form a map */
auto group_by_into_map(R&& range, F&& f)
{
unordered_map<
decay_t<indirect_result_t<F&, iterator_t<R>>>, // result of unary function
vector<range_value_t<R>> // range-as-vector
> map;

for (auto&& e : range) {
map[std::invoke(f, e)].push_back(e);
}

return map;
}

类似的东西。这允许:

group_by_into_map(people, &Person::Age);

除非您同意使用 std::unordered_multimap .人们用那个吗?这是一种奇怪的容器。但假设你是,那么这就容易多了。您可以编写自己的适配器:

template <typename F> // NB: must be unconstrained
auto group_by_into_map(F&& f) {
return views::transform([=](auto&& e){ return std::pair(std::invoke(f, e), e); })
| ranges::to<std::unordered_multimap>();

}

允许:

people | group_by_into_map(&Person::Age);

但这会给你一个 unordered_multimap<int, Person>而不是 unordered_map<int, vector<Person>> .

关于c++ - C++20 范围是否支持按功能分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63942514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com