map定义:
代码语言:javascript复制template < class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key,T> > > class map;
1 Key 和 Value。
2 第四个是 Allocator,用来定义存储分配模型的。 3 第三个参数:class Compare = less<Key>。
什么? map中也可以定义排序算法,还是万能模板,好吧,今后面试排序就靠它类。
代码语言:javascript复制 #include <iostream>
#include <string>
#include <map>
class Name
{
private:
std::string firstname{};
std::string secondname{};
public:
Name(std::string first, std::string second) : firstname{first},
secondname{second}{};
Name()=default;
bool operator>(const Name& name)const
{
return secondname > name.secondname ||
((secondname == name.secondname) &&
(firstname > name.firstname));
}
friend std::ostream& operator<<(std::ostream& out, const Name& name);
};
inline std::ostream& operator<<(std::ostream& out, const Name& name)
{
out << name.firstname " " name.secondname;
return out;
}
int main()
{
std::map<Name,size_t, std::greater<Name>> people{{Name{"Al", "Bedo"}, 53},
{Name{"Woody","Leave"},33},{Name{"Noah", "Lot"}, 43}};
for ( const auto& p : people)
std::cout << p.first << " " << p.second << " n";
return 0;
}
万能?你再来一个看看。
代码语言:javascript复制#include <iostream>
#include <string>
#include <map>
#include <memory>
using std::string;
using namespace std;
class Key_compare
{
public:
bool operator () (const unique_ptr<string>& p1,
const unique_ptr <string>& p2) const
{
return *p1 < *p2;
}
};
int main()
{
//第三个参数用来比较
std::map<unique_ptr<string>,string,Key_compare> phonebook;
//在容器的适当位置直接生成了一个 pair 对象
//14
phonebook.emplace(make_unique<string>("Fred"), "914 626 7897");
//将参数元素移到容器中
phonebook.insert(make_pair(make_unique<string>("Lily"), "212 896 4337"));
for (const auto& p: phonebook)
std:: cout << *p.first << " " << p.second << std::endl;
for (auto iter = std::begin (phonebook) ;iter != std:: end (phonebook) ; iter)
std:: cout << *iter->first << " " << iter->second << std::endl;
return 0;
}