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.
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.
As long as your vector contains elements that in themselves can be compared (have operator== ), this works, yes.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With