gpt4 book ai didi

c++ - 应用函数后查找重复值的函数

转载 作者:行者123 更新时间:2023-11-28 04:39:00 25 4
gpt4 key购买 nike

我想要一个 C++ 函数,它在集合中找到一个与 function(key) 具有相同值的项。作为集合中的另一项。

例如

std::set<int> ints = {1, -1, 3};
// Finds an item in the set with the same absolute value as
// another item.
int* dupe = find_duplicates(ints, [](int x) { return std::abs(x); });
// Should print -1 or 1
if (dupe != 0) std::cout << "Found dupe: " << *dupe << std::endl;

但是,我什至在为此方法编写函数签名时遇到了麻烦。

在 Java 中它类似于 static Integer findDuplicates<T, U>(Iterable<T>, Function<T, U> func) .

在 C++ 中,我得到了以下信息,但它无法编译:

template<template <typename T> Collection, typename U>
T* find_duplicates(
const Collection<T>& collection,
const std::function<U(T)>& func) { ... }

我得到的错误是 error: 'T' does not name a type .

有什么指点吗? (我也对绕过使用指向 T* 的“原始”指针的方法感兴趣,但这对于一个单独的问题可能更好)

最佳答案

在您的示例中,T 无法识别且几乎无用。您应该先引入类型T,然后然后使用它来指定Collection,如下所示:

template<typename T, template <typename> typename Collection, typename U>
T* find_duplicates(const Collection<T>& collection,
const std::function<U(T)>& func)
{
// some logic here
}

另外:请注意您在 Collection 之前错过了一个 typename,正如我之前在评论中指出的那样。上面的示例已根据该建议进行了调整。

关于c++ - 应用函数后查找重复值的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50661696/

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