gpt4 book ai didi

c++ - 在 C++ 中打印元组内的对

转载 作者:行者123 更新时间:2023-12-01 23:05:49 32 4
gpt4 key购买 nike

我试图在一个元组中打印 pair 的所有值,

头文件

template <typename... Args>
void printPairs(std::tuple<Args...> t)
{
for (int i = 0; i <= 4; i++) //the value of 'i' is not usable in a constant expression
{
auto pair = std::get<i>(t);
cout << pair.first << " " << pair.second << endl;
}
}

main.cpp

std::tuple<std::pair<int, int>, std::pair<int, int>, std::pair<int, int>, std::pair<int, int>> t1 = {std::make_pair(1, 2), std::make_pair(3, 4), std::make_pair(5, 6), std::make_pair(7, 8)};
printPairs(t1);

如果您不进行迭代并使用常量值代替“i”,则效果很好

auto pair = std::get<1>(t);
cout << pair.first << " " << pair.second << endl;

最佳答案

您可以使用 std::apply :

template<typename Tuple>
void printPairs(const Tuple& t) {
std::apply([](const auto&... pair) {
((std::cout << pair.first << " " << pair.second << std::endl), ...);
}, t);
}

关于c++ - 在 C++ 中打印元组内的对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70907173/

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