Distribution_Service/CC_SDK/Include/basic/CCVector.h

100 lines
2.3 KiB
C
Raw Normal View History

2025-11-11 17:46:19 +08:00
#ifndef CCVECTOR_H
#define CCVECTOR_H
#include <list>
#include "vector"
#include "mutex"
template<typename T>
class CCVector:public std::vector<T>
{
public:
using std::vector<T>::vector;
CCVector(const std::vector<T> & v) {
this->assign(v.begin(), v.end());
}
CCVector(const std::list<T> & v) {
this->assign(v.begin(), v.end());
}
CCVector(const CCVector<T> & v) {
this->assign(v.begin(), v.end());
}
void append(const std::vector<T> & v) {
for (auto & i : v) {
this->push_back(i);
}
}
void append(const std::list<T> & v) {
for (auto & i : v) {
this->push_back(i);
}
}
/**
*
* @param item
*/
void add_lock(const T& item) {
mutex_.lock();
std::vector<T>::push_back(item);
mutex_.unlock();
}
/**
*
* @param item
*/
void remove_lock(const T& item) {
mutex_.lock();
std::vector<T>::remove(item);
mutex_.unlock();
}
/**
*
*/
void clear_lock() {
mutex_.lock();
std::vector<T>::clear();
mutex_.unlock();
}
/**
*
* @return
*/
const T& get(const int index) {
if (index < 0 || index >= static_cast<int>(this->size())) {
throw std::out_of_range("Index out of range");
}
auto it = this->begin();
std::advance(it, index); // 使用 std::advance 移动迭代器
return *it;
}
CCVector operator=(const CCVector<T>& v) {
this->assign(v.begin(), v.end());
return *this;
}
CCVector operator=(const std::list<T>& v) {
this->assign(v.begin(), v.end());
return *this;
}
CCVector operator=(const std::vector<T>& v) {
this->assign(v.begin(), v.end());
return *this;
}
private:
std::mutex mutex_;
};
// 将 operator<< 定义为非成员函数
template <typename T>
std::ostream& operator<<(std::ostream& os, const CCVector<T>& arr) {
os << "[";
for (size_t i = 0; i < arr.size(); ++i) {
if (i != 0) {
os << ", ";
}
os << arr[i];
}
os << "]";
return os;
}
#endif