gpt4 book ai didi

c++ - 在带有 std::greater 附加参数的 std::map 上使用三元运算符

转载 作者:太空宇宙 更新时间:2023-11-04 14:59:27 25 4
gpt4 key购买 nike

我有两个 std::maps。一个在构造函数中使用 std::greater,因此它按相反的方向排序:

std::map<key, value> map1;
std::map<key, value, std::greater> map2;

目前我有两个函数,每个映射一个,每个迭代元素和处理。但是,鉴于处理逻辑相同(只是 map 迭代方向不同),我想将这两个函数替换为一个函数:

template<bool useMap1>
void combinedFunc()
{
std::map<key, value>& map = useMap1 ? map1 : map2;
std::map<key, value>::iterator iter = map.begin();

// A fair amount of code iterating over the elements, hence wishing to combine
}

但是,编译器正确地说 map1 和 map2 是不兼容的类型。

有没有办法重用代码,即使使用 std::greater?

最佳答案

Is there a way to reuse the code, even with std::greater?

这是一种方法。

  1. 创建两个重载函数来处理这两个映射。
  2. 将处理 map 项的核心逻辑移至另一个使用迭代器的函数。

template <typename Iterator>
void coreFunction(Iterator start, Iterator end) { ... }

// For map1
void functionForMap(std::true_type dummyArgument)
{
coreFunction(map1.begin(), map1.end());
}

// for map2
void functionForMap(std::false_type dummyArgument)
{
coreFunction(map2.begin(), map2.end());
}

template<bool useMap1>
void combinedFunc()
{
functionForMap(std::integral_constant<bool, useMap1>());
}

更简单——这只需要第一个函数。

template<bool useMap1>
void combinedFunc()
{
useMap1 ? coreFunction(map1.begin(), map1.end()) : coreFunction(map2.begin(), map2.end());
}

关于c++ - 在带有 std::greater 附加参数的 std::map 上使用三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57812468/

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