我有以下程序,程序的目的是显示列表向量中每个值的发生次数。
如果元组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;
}
答案 0 :(得分:1)
您无法在未排序的容器上运行二进制搜索。二进制搜索依赖于以下事实:如果中点不是您想要的元素,那么如果它超过中点,则所需的元素将位于上半部分,如果中间点更小,则将位于下半部分。您无法保证使用未分类的容器。
现在不是编写自己的函数来获取每次出现的次数,而是可以使用 <span ng-bind-html="friend.name | customFilter"></span>
<span>{{friend.phone}}</span>
为你做这样的事情
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;
}