Distribution_Service/CC_SDK/Include/basic/CCList.h

125 lines
3.1 KiB
C
Raw Normal View History

2025-11-11 17:46:19 +08:00
#ifndef CCLIST_H
#define CCLIST_H
#include <ostream>
#include "list"
#include "vector"
template<class T>
class CCList :public std::list<T> {
public:
using std::list<T>::list;
CCList(const std::list<T>& v) {
this->assign(v.begin(), v.end());
}
CCList(const std::vector<T>& v) {
this->assign(v.begin(), v.end());
}
CCList(const CCList<T>& v) {
this->assign(v.begin(), v.end());
}
void add(const T& item) {
this->push_back(item);
}
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);
}
}
friend std::ostream &operator<<(std::ostream &os, const CCList<T> &list) {
os<< "[";
for (auto it = list.begin(); it != list.end(); ++it) {
os << *it;
if (std::next(it) != list.end()) {
os << ", ";
}
}
os << "]";
return os;
}
/**
*
* @param item
*/
void add_lock(const T& item) {
mutex_.lock();
std::list<T>::emplace_back(item);
mutex_.unlock();
}
/**
*
* @param item
*/
void remove_lock(const T& item) {
mutex_.lock();
std::list<T>::remove(item);
mutex_.unlock();
}
/**
*
*/
void clear_lock() {
mutex_.lock();
std::list<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;
}
/**
* 线
* @return
*/
T* getPtr(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);
}
const T& operator [] (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;
}
CCList operator=(const CCList<T>& v) {
this->assign(v.begin(), v.end());
return *this;
}
CCList operator=(const std::list<T>& v) {
this->assign(v.begin(), v.end());
return *this;
}
CCList operator=(const std::vector<T>& v) {
this->assign(v.begin(), v.end());
return *this;
}
private:
std::mutex mutex_;
};
#endif