0

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; } 
8
  • 2
    You're missing a return value if they are not different, and return a != b; is a bit nicer than your loop. Commented Dec 17, 2021 at 14:39
  • i corrected it. Thank you Commented Dec 17, 2021 at 14:41
  • 1
    I don't think this would work for something like {1,2,3,5,5}; and {1,1,2,3,5}; for example. Commented Dec 17, 2021 at 14:41
  • @JohnnyMopp there are no duplicated. Sorry I had to add it Commented Dec 17, 2021 at 14:43
  • yes Pete I corrected it Commented Dec 17, 2021 at 14:46

2 Answers 2

4

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()}; } 
Sign up to request clarification or add additional context in comments.

12 Comments

sorry it should be IsAtLeastOneElementDifferent
So checking if the sizes are equal first should fix it, or do you have other constraints?
that's basically it
@Botje I do not know who upvoted this answer but it is a wrong answer. For example the two different vectors { 1, 1, 2 } and { 1, 2, 2 } will be identical according to the approach.
@VladfromMoscow Normally, yes. But OP stated there were no duplicates
|
1

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); }); } 

2 Comments

this is O(n^2) solution.
Now imagine if there were 100000 elements in each vector. This will iterate 10000000000 times.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.