未按预期找到事件

Not finding occurrences as intended

本文关键字:事件      更新时间:2023-10-16

我有下面的程序,这些程序的目的是显示列表向量中每个值发生的次数。

如果元组2:3在向量中出现3次,那么程序会将其显示给用户。

预期输出

  • 0:8发生1次%x
  • 2:3发生3次%x
  • 9:5发生2次%x
  • 8:9发生1次%x

实际输出:

  • 2:3发生3次%42
  • 8:9发生1次%14
  • 9:5发生3次%42

知道我做错了什么吗?以下是我使用的代码的完整且可验证的工作版本

#include <vector>
    #include <iostream>
    #include <tuple>
    using namespace std;
    int counter = 0;
    double percentage;
    int val = 0;
    vector<tuple<int, int>> list = { make_tuple(2, 3), make_tuple(0, 8), make_tuple(2, 3), make_tuple(8, 9), make_tuple(9, 5), make_tuple(9, 5), make_tuple(2, 3) };

         int binarysearch(vector<tuple<int, int>> list, int low, int high, tuple<int, int> number)
         {
            int index = low;
            int mid = 0;
            // loop till the condition is true
            while (low <= high) {
                // divide the array for search
                mid = (low + high) / 2;
                if (list.at(mid) > number) {
                    high = mid - 1;
                }
                else {
                    low = mid + 1;
                }
            }return (high - index + 1);
        }
         int main()
         {
             while (counter <= list.size() - 1) {
                 val = binarysearch(list, counter, list.size() - 1, list.at(counter));
                 percentage = val * 100 / list.size();
                 cout << "Value: " << get<0>(list.at(counter)) << ":" << get<1>(list.at(counter)) << " Occurs: " << val << " Time(s)" << " %" << percentage << endl;
                 counter += val;
             }
             return 0;
         }

不能在未排序的容器上运行二进制搜索。二进制搜索依赖于这样一个事实,即如果中点不是您想要的元素,那么如果中点大于中点,则您想要的图元将位于上半部分,如果中点小于中点,则位于下半部分。你不能用未分类的容器来保证这一点。

现在,不用编写自己的函数来获取每次出现的次数,而是可以像一样使用std::map来实现这一点

std::vector<std::tuple<int, int>> list = { make_tuple(2, 3), make_tuple(0, 8), make_tuple(2, 3), make_tuple(8, 9), make_tuple(9, 5), make_tuple(9, 5), make_tuple(2, 3) };
std::map<std::tuple<int, int>, int> occurrences;
for (const auto& e : list) // go though the vector and add to the map.  increment the value on duplication
    ++occurrences[e];
for (const auto& e : occurrences)
{
    double percentage = e.second * 100 / list.size();
    cout << "Value: " << get<0>(e.first) << ":" << get<1>(e.first) << " Occurs: " << e.second << " Time(s)" << " %" << percentage << endl;
}

哪个输出:

Value: 0:8 Occurs: 1 Time(s) %14
Value: 2:3 Occurs: 3 Time(s) %42
Value: 8:9 Occurs: 1 Time(s) %14
Value: 9:5 Occurs: 2 Time(s) %28