gpt4 book ai didi

c++ - 避免使用容器调用函数列表?

转载 作者:行者123 更新时间:2023-11-30 00:38:08 25 4
gpt4 key购买 nike

我有一个返回 bool 值的函数列表。我想遍历函数列表并为每个“测试 1 通过”、“测试 2 失败”等写一条消息。

我目前的解决方案是创建一个函数指针 vector ,推回每个函数,然后循环遍历该 vector 。下面的代码。有没有一种方法可以避免容器而无需为每个测试重复通用消息(通过/失败)代码(想象一下会有数百个测试)。感觉好像 vector 是不必要的,或者必须有一个更优雅的解决方案。

typedef bool (*Tests)();
std::vector<Tests> tests;
tests.push_back(FASTA_FILE_READER_TEST);
tests.push_back(EXACT_MATCH_TEST);

for (int i = 0; i < tests.size(); i++) {
std::cout << "Test " << i + 1
<< (tests[i]() ? " PASSED" : " FAILED")
<< std::endl;
}

最佳答案

有什么阻碍你使用数组的吗?

#include <iostream>

bool FASTA_FILE_READER_TEST() { return false; }
bool EXACT_MATCH_TEST() { return false; }

int main()
{
typedef bool (*Tests)();

Tests tests[] = {FASTA_FILE_READER_TEST, EXACT_MATCH_TEST};


for (int i = 0; i < sizeof(tests)/sizeof(Tests); i++) {
std::cout << "Test " << i + 1
<< (tests[i]() ? " PASSED" : " FAILED")
<< std::endl;
}
}

关于c++ - 避免使用容器调用函数列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11630782/

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