无法在 std::array 上使用 std::apply

jjc*_*mar 3 c++ arrays apply

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

\n
    std::array<int, 4> fixIndices = {1, 60, 127, 187};\n\n    std::apply(\n        [](int id) {\n            std::cout << id;\n        },\n        fixIndices);\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
/usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/c++/tuple:1727:27: error: no matching function for call to \xe2\x80\x98__invoke(****)::<lambda(int)>, int&, int&, int&, int&)\xe2\x80\x99\n 1727 |       return std::__invoke(std::forward<_Fn>(__f),\n      |              ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~\n 1728 |       std::get<_Idx>(std::forward<_Tuple>(__t))...);\n
Run Code Online (Sandbox Code Playgroud)\n

我缺少什么?

\n

康桓瑋*_*康桓瑋 6

std::apply将 tuple(-like) 中包含的参数转发给 callable f,所以你的 lambda 应该是

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

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


for*_*818 5

std::apply是使用以元组形式给出的参数来调用可调用对象。例如你可以调用一些

auto f = [](int a,double b,char c) {}
Run Code Online (Sandbox Code Playgroud)

std::tuple<int,double,char>. 请注意,std::array它类似于元组,即您可以使用数组来调用需要参数的可调用4对象。

但是,在这里您不需要std::apply. 您可以使用循环:

std::array<int, 4> fixIndices = {1, 60, 127, 187};
auto f = [](int id) { std::cout << id;};
for (const auto& id : fixIndices) f(id);
Run Code Online (Sandbox Code Playgroud)

或者通过以下方式更接近您的代码for_each

std::for_each(fixIndices.begin(),fixIndices.end(), [](int id) { std::cout << id; });
Run Code Online (Sandbox Code Playgroud)

  • 如果您碰巧有 C++20 编译器,您还可以使用 std::ranges::for_each 来避免调用 begin() 和 end() 。 (2认同)