標准庫 set 自定義關鍵字類型與比較函數
問題:哪些類型可以作為標准庫set的關鍵字類型呢???
答案:
1,任意類型,但是需要額外提供能夠比較這種類型的比較函數。
2,這種類型實現了 < 操作。
答案1的詳細說明:聲明set時,除了給出元素類型外,還需要給出一個比較函數的類型,注意是類型,不是變量
方式1:使用decltype,注意后面必須有*
multiset<Book, decltype(compareIsbn)*> bookstore(compareIsbn);//compareIsbn是實際存在的函數名
方式2:直接使用函數指針
multiset<Book, bool (*)(const Book &, const Book &)> bookstore(compareIsbn);//compareIsbn是實際存在的函數名
代碼塊索引:
代碼塊 | 功能描述 |
---|---|
test1 | 對應上面的答案1 |
test2 | 對應上面的答案2 |
例子:
#include <iostream>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <vector>
using namespace std;
class Book{
public:
Book(string bn = "") : isbn(bn){}
const string& getIsbn() const{
return isbn;
}
private:
string isbn;
};
bool compareIsbn(const Book &b1, const Book &b2){
return b1.getIsbn() < b2.getIsbn();
}
class Student{
public:
Student(string n = "", int a = 0) : name(n), age(a){}
bool operator < (const Student &s) const{
return age < s.age;
}
public:
string name;
int age;
};
int main(){
//test1 自定義關鍵字類型,函數方式
/*
//傳遞函數指針的第一種寫法,使用decltype
//multiset<Book, decltype(compareIsbn)*>
// bookstore(compareIsbn);
//傳遞函數指針的第二種寫法,直接使用函數指針
//注意:尖括號里要的是類型,不可以先定義一個函數指針的變量,然后把這個變量放到尖括號里,切記!!!
multiset<Book, bool (*)(const Book &, const Book &)>
bookstore(compareIsbn);
vector<Book> books;
for(char c = '5'; c != '1'; --c){
string tmp = "isbn_0";
tmp.insert(tmp.size(), 1, c);
books.push_back(Book(tmp));
}
for(auto const &s : books){
cout << s.getIsbn() << " ";
}
cout << endl;
bookstore.insert(books.cbegin(), books.cend());
for(auto const &s : bookstore){
cout << s.getIsbn() << " ";
}
cout << endl;
*/
//test2 自定義關鍵字類型,重載<方式
multiset<Student> students;
Student s1("C", 3);
Student s2("A", 5);
Student s3("A", 4);
students.insert(s1);
students.insert(s2);
students.insert(s3);
for(auto const &s : students){
cout << s.name << ": " << s.age << endl;
}
}