您的位置:首页 > 产品设计 > UI/UE

deque的中find自定义的类型

2013-02-23 22:25 183 查看
可以调用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())
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: