// 不会存储key值重复的元素(插入50个,可能元素个数只有18,好多重复)
unordered_set<int> set1;
for (int i = 0; i < 50; ++i)
{
set1.insert(rand()%20+1); // vector/deque/list insert(it, val)
}
//哈希表元素的个数!
//cout << set1.size() << endl;
//值为15的元素的个数!
//cout << set1.count(15) << endl;
auto it1 = set1.begin();
for (; it1 != set1.end(); ++it1)
{
cout << *it1 << " ";
}
cout << endl;
set1.erase(20); // 按key值删除元素
for (it1 = set1.begin(); it1 != set1.end(); )
{
if (*it1 == 30)
{
it1 = set1.erase(it1); // 调用erase,it1迭代器就失效了
}
else
{
++it1;
}
}
it1 = set1.find(20);
if (it1 != set1.end())
{
set1.erase(it1);
}
for (int v : set1)
{
cout << v << " ";
}
cout << endl;
此时size还是3对,因为不允许重复的key(如果有重复的直接覆盖原来的!)
map operator[ ](key) => value 查询
cout << map1[1000] << endl;
map的operator[]
1.查询
2.如果key不存在,它会插入一对数据[key, string()]
V& operator[](const K &key)
{
insert({key, V()});
}
改进:
如果key不存咋,就插入【key,0】,返回的是值(0),然后++,值就变成了1。如果存在这个key,那么返回value,再++。一句代码就是上面的九行代码!
在上面的10万个整数中,把数字进行去重打印,很显然选择unorder_set就可以搞定了!
因为unorder_set是不会存储重复的元素的!
1-19只有19个数,说明不能重复存储!
插入一个类,如何排序?需要给自定义类实现小于(<)运算符的重载函数!:
class Student
{
public:
Student(int id, string name)
:_id(id), _name(name) {}
bool operator<(const Student &stu)const
{
return _id < stu._id;
}
private:
int _id;
string _name;
friend ostream& operator<<(ostream &out, const Student &stu);
};
ostream& operator<<(ostream &out, const Student &stu)
{
out << "id:" << stu._id << " name:" << stu._name << endl;
return out;
}
int main()
{
set<Student> set1;
set1.insert(Student(1020, "李广"));
set1.insert(Student(1000, "张雯"));
for (auto it = set1.begin();it != set1.end(); ++it)
{
cout << *it << endl;
}
/*
set<int> set1;
for (int i = 0; i < 20; ++i)
{
set1.insert(rand()%20+1);
}
for (int v : set1)
{
cout << v << " ";
}
cout << endl;
*/
return 0;
}
class Student
{
public:
Student(int id=0, string name="")
:_id(id), _name(name) {}
private:
int _id;
string _name;
friend ostream& operator<<(ostream &out, const Student &stu);
};
ostream& operator<<(ostream &out, const Student &stu)
{
out << "id:" << stu._id << " name:" << stu._name << endl;
return out;
}
//map默认用key排序的,所以不需要重载<运算符!!!
int main()
{
map<int, Student> stuMap;
stuMap.insert({ 1000, Student(1000, "张雯") });
stuMap.insert({ 1020, Student(1020, "李广") });
stuMap.insert({ 1030, Student(1030, "高洋") });
// stuMap.erase(it) stuMap.erase(1020) stuMap[2000]如果不存在则:自动插入[2000, V()]
// cout << stuMap[1020] << endl; stuMap.find(key)
auto it = stuMap.begin();
for (; it != stuMap.end(); ++it)
{
cout << "key:" << it->first << " value:" << it->second << endl;
}
cout << endl;
return 0;
}