Associative containers, the comparison function is not part of the element type?

I think the mapping function that can be passed to the associative container template, for example, std::setor std::multiset, is not part of the actual element typeinstance of the container-type?

#include <iostream>
#include <set>
#include "Sales_data_ex1119.hpp"
using namespace std;

bool compare_isbn(const Sales_data& lhs, const Sales_data& rhs) {
    return lhs.isbn() < rhs.isbn();
}

int main() {
    using cmp_func = bool (*)(const Sales_data& lhs, const Sales_data& rhs);
    multiset<Sales_data, cmp_func> bookstore(&compare_isbn);
    Sales_data foo("978", 2, 22.22);
    Sales_data foo2("978", 2, 22.22);
    Sales_data bar("979", 3, 22.22);
    Sales_data baz("980", 2, 22.22);

    bookstore.insert(foo);
    bookstore.insert(foo2);
    bookstore.insert(bar);
    bookstore.insert(baz);

    // comparsion function is not part of element type?
    multiset<Sales_data>::iterator it = bookstore.begin();
    while (it != bookstore.end()) {
        print(cout, *it++);
        cout << "\n";
    }
    cout << "\n";

    // but the comparsion function can be applied also
    multiset<Sales_data, cmp_func>::iterator it2 = bookstore.begin();
    while (it2 != bookstore.end()) {
        print(cout, *it2++);
        cout << "\n";
    }   

    return 0;
}

Both definitions, itand it2compile and run with GCC 7. I think that key_typeis defined as Sales_dataand key_typefor std::setand std::multisetis element type.
If you've seen a lot of people using the sort function in a definition, which is probably just more explicit, but not necessary.

thank

+4
source share
1 answer

, comparsion, , std:: set std:: multiset, ?

multiset<Key,Compare,Allocator> multiset<Key,Compare,Allocator>::iterator.

, node , , , , , , - , (multi) (set | map) .

, , . , :

multiset<Sales_data, cmp_func> bookstore(&compare_isbn);
multiset<Sales_data>::iterator it = bookstore.begin();

, . , .

, Compare ( Allocator!), .

auto it = bookstore.begin()

. , :

for (auto &sale : bookstore) {

copy(begin(bookstore), end(bookstore),
     ostream_iterator<Sales_data>(cout, "\n"));
+4

Source: https://habr.com/ru/post/1695361/


All Articles