Can I use ' == ' to compare two vectors. I tried it and seems to be working fine. But I don't know whether it will work in more complex situations

前端 未结 6 1195
予麋鹿
予麋鹿 2021-02-01 12:30

First example:

int main(){
    using namespace std;   
    vector v1{10, 20, 30, 40, 50};
    vector v2{10, 20, 30, 40, 50};

    if(v1==v2         


        
6条回答
  •  醉话见心
    2021-02-01 12:58

    Be advised that vectors are ordered, and std::equal or the == operator check that the vectors have the same contents in the same order. For many use cases this might be enough.

    But there might be occasions when you want to know if two vectors have the same contents but not necessarily in the same order. For that case you need another function.

    One nice and short implementation is the one below. It was suggested here: https://stackoverflow.com/questions/17394149/how-to-efficiently-compare-vectors-with-c/17394298#17394298 There you will also find a discussion on why you might not want to use it...

    Put this in a header file of your choice:

    #include 
    
    template 
    static bool compareVectors(std::vector a, std::vector b)
    {
       if (a.size() != b.size())
       {
          return false;
       }
       ::std::sort(a.begin(), a.end());
       ::std::sort(b.begin(), b.end());
       return (a == b);
    }
    

    And here an example illustrating the above theory:

    std::vector vector1;
    std::vector vector2;
    
    vector1.push_back(100);
    vector1.push_back(101);
    vector1.push_back(102);
    
    vector2.push_back(102);
    vector2.push_back(101);
    vector2.push_back(100);
    
    if (vector1 == vector2)
       std::cout << "same" << std::endl;
    else
       std::cout << "not same" << std::endl;
    
    if (std::equal(vector1.begin(), vector1.end(), vector2.begin()))
       std::cout << "same" << std::endl;
    else
       std::cout << "not same" << std::endl;
    
    if (compareVectors(vector1, vector2))
       std::cout << "same" << std::endl;
    else
       std::cout << "not same" << std::endl;
    

    The output will be:

    not same
    not same
    same
    

提交回复
热议问题