Compare two objects in vector iteration C++

时间:2018-03-25 20:45:33

标签: c++ vector comparison-operators

How to implement the comparison function in this case?

void remove(const Object1 &object1) {
    for(auto &object2 : objectVector) {
        if(object1 == object2) {
            /*....... */
        }
    }
} 

3 个答案:

答案 0 :(得分:1)

你问了两个问题:

  1. 如何使对象具有可比性:
  2. 通过为班级实施operator==。请务必暂时覆盖operator !=

    作为会员功能:

    bool Object1::operator ==(const Object1 &b) const
    {
        // return true if *this equals b;
    }
    

    或作为免费功能:

    bool operator ==(const Object1 &a, const Object1 &b)
    
    1. 如何从矢量中删除具有给定值的对象:
    2. 最简单的方法是使用std::remove

      objectVector.erase(std::remove(objectVector.begin(), objectVector.end(), object1), objectVector.end());
      

      您可以在迭代向量时删除对象,但是必须记住向量迭代器随后失效。你可能不会再对载体进行迭代。

答案 1 :(得分:0)

如果object是一个类,你可以在类中覆盖operator ==作为友元函数,或者你可以实现自己的函数bool isEqual(Object1 o1,Object1 o2){if(something)return true;返回false; }

答案 2 :(得分:0)

你班级的一个对象可以包含不同类型和数量的成员,所以假设你有一个班级A

class A{
    int x,
    float y;
    char* z;
};

你有两个实例:

A a1;
A a2;

比较:

if(a1 == a2) // compile-time error
    ;// DoSomeThing

上面你得到错误,因为编译器不知道哪些字段将相互比较。解决方案是重载equals运算符“==”以处理类的对象。

class Student{
    public:
        Student(std::string, int age);
        std::string getName()const;
        int getAge()const;

        bool operator == (const Student&);
    private:
        std::string name;
        int age;
};

Student::Student(std::string str, int x) : 
    name(str), age(x){
}

bool Student::operator == (const Student& rhs){
    return age == rhs.age;  
}

std::string Student::getName()const{
    return name;
}

int Student::getAge()const{
    return age;
}


int main(){


    Student a("Alpha", 77);
    Student b("Beta", 49);

    if(a == b)
        std::cout << a.getName() << " is the same age as " << 
        b.getName() << std::endl;


    cout << endl << endl;
    return 0;
}
  • 现在,编译器知道如何比较类的对象,并知道equals运算符在ojects成员上的比较。