c++ - 不能在 std::array 上使用 std::apply

我正在尝试将 lambda 应用于 std::array 的元素。

    std::array<int, 4> fixIndices = {1, 60, 127, 187};

    std::apply(
        [](int id) {
            std::cout << id;
        },
        fixIndices);

但是,这个简单的代码无法编译

/usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/c++/tuple:1727:27: error: no matching function for call to ‘__invoke(****)::<lambda(int)>, int&, int&, int&, int&)’
 1727 |       return std::__invoke(std::forward<_Fn>(__f),
      |              ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
 1728 |       std::get<_Idx>(std::forward<_Tuple>(__t))...);

我错过了什么?

最佳答案

std::apply将元组中包含的参数(类似)转发给可调用的 f,因此您的 lambda 应该是

std::array<int, 4> fixIndices = {1, 60, 127, 187};
std::apply(
  [](auto... ids) {
     ((std::cout << ids << " "), ...);
  }, 
  fixIndices);

但对于 std::array,如果您想遍历它的元素,基于范围的 for 循环是一个更简单的选择。

https://stackoverflow.com/questions/72025515/

相关文章:

c++ - std::ranges::to 是否允许转换为 std::map?

c++ - 用 CString 替换 LPCTSTR 是否安全?

haskell - 为什么不是 (20 >) 。长度 。取 10 === const True

module - 是否有一种简洁/内联的方式来创建 Set 值而不显式命名它们的类型?

python - 如何找到具有最少步数的元素

postgresql - Prisma 生成的类型不更新

nuxt.js - 如何在 Nuxt 3 中间件获取当前域?

r - 在嵌套列表中从第一个列表中选择第一个元素,从第二个列表中选择第二个元素,依此类推

r - 使用 Slice 或 Stringr 更改 R 中字符串向量中特定字符串的位置?

ios - Xcode 构建失败 : Requested but did not find exte