读书人

deque的中find自定义的部类

发布时间: 2013-02-24 17:58:56 作者: rapoo

deque的中find自定义的类型

可以调用find()在deque中查找。

对应值类型如int类型 可以直接使用。

对应自定义的类和结构须添加bool operator == (const MyClass &other) const 成员函数或bool operator ==(const MyClass &one, const MyClass &another)全局函数。

class MyClass{public:int a;int b;//bool operator == (const MyClass &other) const         //{//    return (a == other.a) && (b == other.b) ;         //}};bool operator ==(const MyClass &one, const MyClass &another) {    return (one.a == another.a)&& (one.b == another.b);}


以下是调用代码

MyClass c;c.a=2;c.b =2;deque<MyClass>::iterator pos;pos = find(clsDeq.begin(), clsDeq.end(), c);if (pos != clsDeq.end())      printf("clsDeq %d success\n", (*pos).a);  else      printf("find failed\n");  


关于内存泄露的考虑

如deque中存储的为非指针类型如上deque<MyClass>或deque<int>

如果容器中含有元素,则程序退出前须清空调用deque的clear()或~deque(),否则出现内存泄露。用VS2008调试会看到Detected memory leaks!。

这种泄露可能在程序运行时没有什么影响。

如deque中存储的是指针类型deque<MyClass*>

每个指针对应一个堆内存。

则需要使用遍历每一个元素并调用delete *iterator;来释放指针指向内存。

然后在清空容器(deque的clear()或~deque())

读书人网 >编程

热点推荐