实现原理
使用map与vector混合的方式实现map的下标索引获取值功能。需要注意的是模板传参中第二个参数的第一个对象做key值要保持数据格式一致,如果不理解这句话的涵义请查看add函数。
参考源码
#ifndef VECTOR_MAP__H_
#define VECTOR_MAP__H_
#include <map>
#include <vector>
#include <thread>
#include <mutex>
#include <iostream>
#ifndef LOGOUT
#define LOGOUT printf
#endif
template<class T1, class T2>
class VectorMap {
private:
//数据存储容器
std::map<T1, T2> mDataMap;
std::vector<T2> mDataVector;
//数据存储容器锁
mutable std::mutex mDataMutex;
public:
VectorMap() {}
virtual ~VectorMap() {}
public:
/*
* @brife 添加数据
* @param info 数据信息
* */
virtual void add(const T2& info)
{
std::lock_guard<std::mutex> lock(mDataMutex);
//T2的开头放入一个T1型数据做key值
const T1 key = *(T1*)&info;
mDataMap[key] = info;
//同步数据到vector便于通过索引值查找数据
mDataVector.clear();
for (auto it : mDataMap)
{
mDataVector.push_back(it.second);
}
}
/*
* @brife 查找数据
* @param id 数据id
* @param info 出参数据信息
* @return true 查找成功;false 查找失败
* */
const bool getById(const T1& id, T2& info) const
{
std::lock_guard<std::mutex> lock(mDataMutex);
auto it = mDataMap.find(id);
if (mDataMap.end() != it)
{
info = it.second;
return true;
}
return false;
}
/*
* @brife 查找数据
* @param index 索引值
* @param info 出参数据信息
* @return true 查找成功;false 查找失败
* */
const bool getByIndex(const uint32_t& index, T2& info) const
{
std::lock_guard<std::mutex> lock(mDataMutex);
if (mDataVector.size() <= index)
{
LOGOUT("--%d-- --%s-- size:%u index:%u 索引越界!!!\n", __LINE__, __FILE__, mDataVector.size(), index);
return false;
}
info = mDataVector[index];
return true;
}
/*
* @brife 查找数据
* @param index 索引值
* @return 返回数据信息
* */
const T2 operator[](uint32_t index) const
{
std::lock_guard<std::mutex> lock(mDataMutex);
if (mDataVector.size() <= index)
{
LOGOUT("--%d-- --%s-- size:%u index:%u 索引越界!!!\n", __LINE__, __FILE__, mDataVector.size(), index);
return T2();
}
return mDataVector[index];
}
/*
* @brife 删除数据
* */
void clear(void)
{
std::lock_guard<std::mutex> lock(mDataMutex);
mDataMap.clear();
mDataVector.clear();
LOGOUT("--%d-- --%s-- 清除容器数据\n", __LINE__, __FILE__);
}
/*
* @brife 获取数据长度
* @return 返回数据长度
* */
const uint32_t size(void) const
{
std::lock_guard<std::mutex> lock(mDataMutex);
return mDataVector.size();
}
};
int main(void)
{
VectorMap<int, int> mVectorMap;
mVectorMap.add(10086);
mVectorMap.add(10010);
mVectorMap.add(10000);
std::cout << "size:" << mVectorMap.size() << std::endl;
for (uint32_t level1 = 0; level1 < mVectorMap.size(); ++level1)
{
std::cout << "index:" << level1 << "\tval:" << mVectorMap[level1] << std::endl;
}
return 0;
}
#endif /* VECTOR_MAP__H_ */