I have the following program, the programs purpose is to display how many times each value in the list vector occurred.
if the tuple 2:3 occurs 3 times in the vector, then the program displays this to the user.
Expected output
Actual Output:
Any idea what I'm doing incorrectly? Here's a complete and verifiable working version of the code I'm using
#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;
}
You cannot run a binary search on an unsorted container. A binary search relies on the fact that if the midpoint is not the element you want then the element you want will be in the top half if it is more than the midpoint and the bottom half if it is less. You cannot guarantee that with an unsorted container.
Now instead of writing your own functions to get the number of each occurrence you can use a std::map
to do that for you like
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;
}
Which outputs:
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