未按预期查找事件

Not finding occurrences as intended

我有以下程序,该程序的目的是显示列表向量中每个值出现的次数。

如果元组 2:3 在向量中出现 3 次,则程序会向用户显示。

预期输出

实际输出:

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

#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