-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVector.hpp
91 lines (73 loc) · 1.55 KB
/
Vector.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//
// Created by lining on 2023/5/29.
//
#ifndef VECTOR_H
#define VECTOR_H
#include <vector>
#include <thread>
#include <mutex>
using namespace std;
template<typename T>
class Vector {
public:
Vector() {
if (mtx == nullptr){
mtx = new std::mutex();
}
}
Vector(unsigned int max) {
if (mtx == nullptr){
mtx = new std::mutex();
}
setMax(max);
}
~Vector() {
delete mtx;
}
bool push(T t) {
std::unique_lock<std::mutex> lock(*mtx);
//先将数据压入
q.push_back(t);
//当设定最大值的时候,如果达到最大值,将头部数据删除
if (isSetMax) {
if (q.size() > max) {
q.erase(q.begin());
}
}
return true;
}
bool getIndex(T &t, int index) {
if ((q.size() < (index + 1)) || index < 0 || q.empty()) {
return false;
}
std::unique_lock<std::mutex> lock(*mtx);
t = q.at(index);
return true;
}
void eraseBegin() {
if (!q.empty()) {
std::unique_lock<std::mutex> lock(*mtx);
q.erase(q.begin());
}
}
void setMax(int value) {
max = value;
isSetMax = true;
}
int size() {
return q.size();
}
bool empty() {
return q.empty();
}
void clear() {
vector<T> q1;
swap(q, q1);
}
private:
int max;
bool isSetMax = false;
vector<T> q;
std::mutex *mtx= nullptr;
};
#endif //VECTOR_H