- /*
- * MyCollection.h
- * vector<>太难用了,自己写一个简单的。
- * ――――“珠海超级郭大侠”(http://weibo.com/gophern)亲手编制
- * Created on: Feb 19, 2014
- * Author: Gophern
- */
- #ifndef __Gophern_MyCollection_h__
- #define __Gophern_MyCollection_h__
- #include <pthread.h>
- typedef void * VoidPtr;
- class MySet {
- public: //暂时用“public”,以利调试
- VoidPtr *elemBuf;
- pthread_mutex_t mutex;
- protected:
- int elemNum;
- int bufSize;
- int bufIncretment;
- public: //<<Proterties>>
- int getElemNum() {
- return elemNum;
- }
- private:
- void init(){
- elemBuf = NULL;
- elemNum = 0;
- bufSize = 0;
- }
- void destroy(){
- if (elemBuf) {
- delete elemBuf;
- elemBuf = NULL;
- elemNum = 0;
- bufSize = 0;
- }
- }
- public:
- MySet() {
- bufIncretment = 16;
- pthread_mutex_init(&mutex,NULL);
- init();
- }
- MySet(int iBufIncretment) {
- bufIncretment = iBufIncretment;
- pthread_mutex_init(&mutex,NULL);
- init();
- }
- ~MySet(){
- destroy();
- pthread_mutex_destroy(&mutex);
- }
- VoidPtr get(int index){
- if (index<0 || index>=elemNum)
- return NULL;
- return elemBuf[index];
- }
- void add(void *elem) {
- if (elemNum + 1 > bufSize) {
- int newBufSize = bufSize + bufIncretment;
- VoidPtr *newElemBuf = new VoidPtr[newBufSize];
- printf("new newElemBuf[%d] %p\\n", newBufSize, newElemBuf);
- memcpy(newElemBuf, elemBuf, elemNum*sizeof(VoidPtr));
- if (elemBuf) {
- printf("delete elemBuf[%d] %p\\n", bufSize, elemBuf);
- delete elemBuf;
- }
- elemBuf = newElemBuf;
- bufSize = newBufSize;
- }
- elemBuf[elemNum] = elem;
- elemNum++;
- }
- void remove(int index) {
- if (index < 0 || index >= elemNum)
- return;
- for (int i = index; i < elemNum - 1; i++) {
- elemBuf[i] = elemBuf[i + 1];
- }
- elemBuf[elemNum - 1] = NULL;
- elemNum--;
- }
- void remove(void *elem) {
- for (int index = 0; index < elemNum; index++) {
- if (elemBuf[index] == elem) {
- for (int i = index; i < elemNum - 1; i++) {
- elemBuf[i] = elemBuf[i + 1];
- }
- elemBuf[elemNum - 1] = NULL;
- elemNum--;
- break;
- }
- }
- }
- };
- #endif /* __Gophern_MyCollection_h__ */
- //该片段来自于http://www.codesnippet.cn/detail/1908201410266.html
来源: http://www.codesnippet.cn/detail/1908201410266.html