本文主要是介绍C++实现简单的string dictionary,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
为什么重复造轮子?
在windows平台下,如果在动态库的接口中使用std::map或其它std容器,会导致崩溃或其它内存问题,所以自己实现一个简单够用能用的key->value字典(map)就很有必要。
#define DEFAULT_ARRAY_LEN 16struct XDictionary
{struct kv_item {void operator=(kv_item& src){key = src.key;value = src.value;}XString key;XString value;};XDictionary(): m_size(0), m_maxSize(0), m_array(NULL){create(DEFAULT_ARRAY_LEN);}~XDictionary(){release();}bool create(uint32_t arraySize){m_maxSize = arraySize;m_size = 0;m_array = new kv_item[m_maxSize];if (m_array == NULL){return false;}return true;}void release(){if (m_array != NULL){delete[] m_array;m_array = NULL;}m_maxSize = 0;m_size = 0;}bool reCreateArray(){const uint32_t increaseStepSize = 8;uint32_t newSize = m_maxSize + increaseStepSize;kv_item* newArray = new kv_item[newSize];if (newArray == NULL){return false;}for (uint32_t i = 0; i < m_maxSize; i++){newArray[i] = m_array[i]; // 拷贝旧数据}delete[] m_array;m_array = newArray;m_maxSize = newSize;return true;}void push(const char* key, const char* value){if (m_size >= m_maxSize){reCreateArray();}m_array[m_size].key.copy(key);m_array[m_size].value.copy(value);m_size++;}uint32_t getRealSize(){return m_size;}kv_item* getItem(uint32_t index){if (index >= m_size){return NULL;}return &m_array[index];}bool isEmpty() const{return (m_size == 0);}uint32_t m_size;uint32_t m_maxSize;kv_item* m_array;
};
XString的实现:C++实现简单的string-CSDN博客
其它容器:C++实现简单的string array-CSDN博客
这篇关于C++实现简单的string dictionary的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!