C++ 缓存再排序,解决多线程处理后的乱序问题,不知道思路对不对[挠下巴]
使用map默认会根据key排序的原理作缓存,队列满了依次推出,抛弃掉过时的数据
bash
#include <functional>
#include <iostream>
#include <map>
#include <random>
#include <set>
#include <tuple>
#include <vector>
template <typename V> class SortQueue {
private:
std::function<void(const int, V &)> callback;
std::map<int, V> m;
int max_size;
int last;
public:
SortQueue(int max) : max_size(max), last(0) {}
~SortQueue() {}
void setCallback(std::function<void(const int, V &)> callback) {
this->callback = callback;
}
void push(int k, V &v) {
if (k < last)
return;
m.emplace(std::make_pair(k, std::move(v)));
if (m.size() > max_size) {
auto it = m.begin();
if (callback) {
callback(it->first, it->second);
last = it->first;
}
m.erase(it);
}
}
};
std::vector<int> r(int start, int end, int size) {
std::set<int> generated_nums; // 存储已生成的随机数
std::vector<int> nums;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> dis(start, end);
while (generated_nums.size() < size) { // 生成10个不重复的随机数
int random_num = dis(gen);
if (generated_nums.find(random_num) == generated_nums.end()) {
generated_nums.insert(random_num);
nums.push_back(random_num);
}
}
return std::move(nums);
}
void p(std::vector<int> &arr) {
std::string result;
for (int i = 0; i < arr.size(); ++i) {
result += std::to_string(arr[i]) + " ";
if ((i + 1) % 10 == 0) {
result += "\n";
}
}
std::cout << "拼接后的字符串: \n" << result << std::endl;
}
int main(int argc, char *argv[]) {
std::vector<int> nums;
int start = 1;
int end = 0;
int size = 10;
for (int i = 0; i < 5; i++) {
start = i * size + 1;
end = i * size + 10;
std::vector<int> temp = r(start, end, size);
nums.insert(nums.end(), temp.begin(), temp.end());
}
// std::vector<int> nums = r(1, 50, 50);
p(nums);
SortQueue<int> sq(5);
sq.setCallback(
[](const int k, int &v) { std::cout << "K: " << k << std::endl; });
for (int num : nums) {
sq.push(num, num);
}
return 0;
}