您的位置:首页 > 编程语言 > Go语言

find方法in algorithm和stl vector同时使用

2010-12-01 16:45 197 查看
刚用stl,很久之前学过的,但是很久没用了,最近做项目需要,随便写测试程序的时候发现不看确实不行。

一个类型的对象能被放入容器,且支持容器的各项操作,需要符合下列条件:

对象的构造和拷贝

● 容器的insert、assign 等操作实际上是对一个对象的副本进行操作

● 一个类型的对象能被放入容器、且支持容器的各项操作,需符合下列条件:

● (最好)有默认构造函数

● 必须有复制构造函数

● 必须有T& operator=(const T& other) 形式的赋值操作

比较操作
● 基于RB­Tree的关联容器是有序的,为保证对容器中的元素或key进行排序,容器中的对象或key必须保证 < 可用,或提供合适的cmp比较器
● 对于部分操作如find,需对比较容器中的元素是否相等,容器中的对象必须保证 == 可用,或结合!cmp(x,y) && !cmp(y,x)

由于在使用find方法时,并没有实现operator==,所以显然无法比较。

先来看例子程序错误的写法吧:

//main:
TestChild *child1 = new TestChild();
child1->SetValue(1);
TestChild *child2 = new TestChild();
child2->SetValue(2);
TestChild *child = new TestChild();
child->SetValue(1);
vector<TestChild *> childList;
childList.push_back(child1);
childList.push_back(child2);
vector<TestChild *>::iterator pos;
pos = find(childList.begin(),childList.end(),child);
if(pos != childList.end())
childList.erase(pos);
unsigned int i = 0;
for(i = 0 ; i < childList.size(); i++)
childList[i]->TestInline();


在这里TestChild是已经实现好的类,其中的方法实现代码如下:

TestChild::TestChild(const TestChild& child)
{
m_value = child.m_value;
}
void TestChild::Run()
{
printf("child class is running ~/n");
}
bool TestChild::operator==(const TestChild& child)
{
return m_value == child.m_value;
}
void TestChild::TestInline()
{
printf("testing inline ~/n");
}


通过http://www.cplusplus.com/reference/algorithm/find/中查看find方法的实现:

template<class InputIterator, class T>
InputIterator find ( InputIterator first, InputIterator last, const T& value )
{
for ( ;first!=last; first++) if ( *first==value ) break;
return first;
}


first是指向vector中内容元素的指针,这样*first取出元素后为指针,而按照

上面例子中,查找的元素也为对象指针,所以实际上进行的是指针与指针之间的比较,

这样就不会调用我们实现的operator==方法了。所以正确的做法应该如下:

//main:
TestChild *child1 = new TestChild();
child1->SetValue(1);
TestChild *child2 = new TestChild();
child2->SetValue(2);
TestChild *child = new TestChild();
child->SetValue(1);
vector<TestChild> childList;
childList.push_back(*child1);
childList.push_back(*child2);
vector<TestChild>::iterator pos;
pos = find(childList.begin(),childList.end(),*child);
if(pos != childList.end())
childList.erase(pos);
unsigned int i = 0;
for(i = 0 ; i < childList.size(); i++)
childList[i].TestInline();


应该使用对象比较而非指针比较。

注意:

当然在使用map是key,value对中,如果value是自己定义的类对象,那么根据上面的说法,实现拷贝构造,=即可,但是key如果也是类对象,那么至少也要实现< operator吧,这个没测试过 。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: