如果调用了 std::map 中的每个键,如何更有效地检查

How to check more efficiently if every key in a std::map has been called

我知道标题很奇怪,但我不知道怎么说,这里是我通常使用的一个非常糟糕的例子:

void exercise1(std::vector<bool> &MyVec) {
    std::cout << "Exercise 1";

    MyVec.at(0) = true;
}

void exercise2(std::vector<bool> &MyVec) {
    std::cout << "Exercise 2";

    MyVec.at(1) = true;
}

int main() {
    int answer;
    std::map<int, std::function<void(std::vector<bool> &MyVec)>> exercises = {
        {1, exercise1},
        {2, exercise2}
    };
    std::vector<bool> wasSeen(2);

    std::fill(wasSeen.begin(), wasSeen.end(), false);

    // assuming the user can only input the digits 1 and 2
    do {
        std::cout << "What exercise do you want to look at?\n (1 to 2)";
        std::cin >> answer;

        exercises.at(answer)(wasSeen);
    } while (std::adjacent_find(wasSeen.begin(), wasSeen.end(), std::not_equal_to<>()) != wasSeen.end());
    
    // do other stuff after all the functions get called

    system("pause>0");
}

是否有比使用 bool 向量 wasSeen 更有效的方法来检查是否调用了映射 中的每个 函数并且总是检查其所有值?

您可以使用 std::set 来存储您已调用的函数的索引。因为 a std::set 只存储唯一元素,所以你知道当 set 的大小等于 map 的大小时所有的函数都被调用了:

 std::set<int> already_called_funcs;

 do {
     int index = my_random_index();
     exercises[index](some_vector);
     already_called_funcs.insert(index);
 } while( already_called_funcs.size() != exercises.size());

但是,如果您只想在循环内调用每个函数一次,您实际上应该做相反的事情:用所有可能的索引填充一个容器,然后从该容器中选择一个随机元素,调用相应的函数,然后删除来自容器的索引。这样,您就不必重新滚动随机数,直到找到以前未使用过的索引。