gpt4 book ai didi

c++ - 仅当语句匹配时如何将参数发送给函数?

转载 作者:太空狗 更新时间:2023-10-29 20:33:07 28 4
gpt4 key购买 nike

我有一张 map ,如果其中包含元素,我只想将其发送给函数。该函数采用一个参数包,因此我可以发送我想要的元素数量或数量。

有没有办法在调用本身中检查 map 的大小?同一个调用中会发送很多 map ,这意味着在调用本身之外进行检查会非常乏味。

我想要的伪代码:

std::map<int, int> a;
std::map<int, int> b;
std::map<int, int> c;
std::map<int, int> d;
fun( (if (a.size() > 0), (if (b.size() > 0), (if (c.size() > 0), (if (d.size() > 0));

我知道这段代码是错误的,但这只是为了让您了解我所追求的。

最佳答案

例如,您可以在 std::initalizer_list(或 std::vector,无论您喜欢什么)中传递映射。然后在函数 a() 中循环遍历每个 map 并检查它是否为空:

#include <initializer_list
#include <iostream>
#include <map>

void a(std::initializer_list<std::map<int, int>> maps)
{
for (const auto& m : maps) {
if (m.empty()) {
std::cout << "was empty\n";
}
else {
std::cout << "was not empty\n";
}
}
}

int main()
{
std::map<int, int> foo1;
std::map<int, int> foo2;
std::map<int, int> foo3;
std::map<int, int> foo4;

foo1[5] = 1;
foo2[9] = 3;

a({foo1, foo2, foo3, foo4});

return 0;
}

Output:

was not empty
was not empty
was empty
was empty

See it live

关于c++ - 仅当语句匹配时如何将参数发送给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57270357/

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