Home > Software design >  C 11 Check if at least one element in vector is not in another vector
C 11 Check if at least one element in vector is not in another vector

Time:12-18

I wrote the following code in order to check if at least one element in vector is not in another vector.

There are no duplicates in the vectors. Only unique elements

Is there a more elegant way to do it by using the stl?

// Online C   compiler to run C   program online
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool areVectorsDifferent(vector<int> &a, vector<int> &b){
    if(a.size() != b.size()){
        return true;
    }
    std::sort(a.begin(),a.end());
    std::sort(b.begin(),b.end());
    for(int i = 0; i < a.size();i  ){
        if(a[i] != b[i]) {
            return true;
        }
    }
  return false;
}

int main() {
    bool isDifferent = false;
    vector<int> a = {1,2,3,5};
    vector<int> b = {4,3,2,1};
    std::cout << areVectorsDifferent(a,b) << std::endl;
    return 0;
}

CodePudding user response:

It depends on your definition of "different", but:

bool areVectorsDifferent(const vector<int> &a, const vector<int> &b){
    return a.size() != b.size()
        || std::set<int>{a.cbegin(), a.cend()} != std::set<int>{b.cbegin(), b.cend()};
}

CodePudding user response:

I hope this solves your problem:


using namespace std;

template <typename T>
auto are_different(const vector<T>& lhs, const vector<T>& rhs) -> bool {
    return lhs.size() != rhs.size() ||
           any_of(cbegin(lhs), cend(lhs), [&rhs](const auto& item) {
               return find(cbegin(rhs), cend(rhs), item) == cend(rhs);
           });
}
  •  Tags:  
  • c
  • Related