【问题标题】:How to check more efficiently if every key in a std::map has been called如果 std::map 中的每个键都已被调用,如何更有效地检查
【发布时间】:2021-07-25 15:34:30
【问题描述】:

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

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 并始终检查其所有值更有效的方法来检查地图中的每个 函数 是否已被调用? p>

【问题讨论】:

  • 最好定义 set 并将输入保留在 set 中并检查该输入是否已被处理。
  • 您可以在地图中的函数旁边存储一个布尔值(作为 std::pair)。当访问条目时,如果标志为假,则将其设置为真并增加一个计数器(即,您为每个条目增加一次计数器)。然后你所要做的就是将计数器的值与地图的大小进行比较。
  • @JonathanPotter 你能提供一些代码示例吗?我从来没有使用过你提到的任何功能

标签: c++ arrays performance vector mapping


【解决方案1】:

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

 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());

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

【讨论】:

  • 如果用户在使用 std::set 时选择看两次相同的练习会发生什么?情况并非如此,这只是一个示例,但我想知道如果有人在集合中插入一个已经存在的值会发生什么
  • std::set 中的@akaManen 元素是唯一的。如果该集合包含例如1,并且您插入1,那么之后该集合仍然包含一个1(插入返回一个bool,它告诉您插入是否实际发生)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-24
  • 1970-01-01
  • 1970-01-01
  • 2013-05-08
相关资源
最近更新 更多