未按预期找到事件
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
相关文章:
- Android NDK传感器向事件队列报告奇怪的间隔
- 从文本文件中读取时钟时间和事件时间并进行处理
- WMI检测进程创建事件-c++
- EvtExportLogneneneba API正在将远程计算机的事件日志保存到远程PC本身.如何将其保存到主机
- 处理闪烁窗口事件
- C++Builder中的OnClick事件签名存在问题
- 跟踪滚动条上的鼠标事件
- 什么是事件表 (wxWidgets)?
- 如何在 MFCaptureEngine 中获取"Camera removed"事件
- 给定顺序中的事件处理
- 当服务中的事件被触发时,如何将响应从服务发送回客户端?
- 在 C++/CLI 中将 .NET 事件从一个 DLL 引发到另一个 DLL
- 如何创建事件驱动的 SDL2 应用程序
- Windows 进程间同步类似事件?
- 如何从C++端挂接到 QML 项的 onClick 事件
- 如何通过多类"Union variable" (sfml) 使用轮询事件
- 如何在Qt 4.8中阻止/忽略/丢弃早于特定超时的用户输入事件
- C++ 信号和插槽不工作:插槽不响应事件
- 在虚幻引擎中触发C++ dll的事件
- 具有Qt事件循环的可移植通用共享库设置