Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two vectors C++

Tags:

I was wondering is there any function to compare 2 string vectors to return the number of different(or the same) elements? Or i have to iterate over both of them and test item by item.
Thanks.

like image 612
Adrian Avatar asked Mar 07 '11 22:03

Adrian


People also ask

Can you compare two vectors?

A vector quantity has two characteristics, a magnitude and a direction. When comparing two vector quantities of the same type, you have to compare both the magnitude and the direction. On this slide we show three examples in which two vectors are being compared. Vectors are usually denoted on figures by an arrow.

Can you do == with vectors?

As long as your vector contains elements that in themselves can be compared (have operator== ), this works, yes.

How do you compare two elements in a vector?

Comparing two vectors using operator == std::vector provides an equality comparison operator==, it can be used to compare the contents of two vectors. For each element in the vector it will call operator == on the elements for comparisons.


1 Answers

std::sort(v1.begin(), v1.end()); std::sort(v2.begin(), v2.end()); std::vector<string> v3; std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v3)); 

Or, if you don't want to sort:

std::set<string> s1(v1.begin(), v1.end()); std::set<string> s2(v2.begin(), v2.end()); std::vector<string> v3; std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), std::back_inserter(v3)); 

You may want to use a multiset if there could be duplicates in a vector.

like image 155
Erik Avatar answered Oct 12 '22 22:10

Erik