Comparing containers

If you have two containers of data, there are various ways that you can compare them. For every container type, there are <, <=, ==, !=, >, and >= operators defined. The == and != operators compare the containers, both in terms of how many items they have and the values of those items. So, if the items have different numbers of items, different values, or both, then they are not equal. The other comparisons prefer values over the number of items:

    vector<int> v1 { 1,2,3,4 }; 
vector<int> v2 { 1,2 };
vector<int> v3 { 5,6,7 };
cout << boolalpha;
cout << (v1 > v2) << endl; // true
cout << (v1 > v3) << endl; // false

In the first comparison, the two vectors have similar items, but v2 has fewer, so v1 is "greater than" v2. In the second case, v3 has larger values than v1, but fewer of them, so v3 is greater than v1.

You can also compare ranges with the equal function. This is passed two ranges (which are assumed to be the same size, so only an iterator to the start of the second range is needed), and it compares corresponding items in both ranges using the == operator for the type accessed by the iterator, or a user-supplied predicate. Only if all such comparisons are true will the function return true. Similarly, the mismatch function compares corresponding items in two ranges. However, this function returns a pair object with iterators in each of the two ranges for the first item that is not the same. You can also provide a comparison function. The is_permutation is similar in that it compares the values in two ranges, but it returns true if the two ranges have the same values but not necessarily in the same order.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset