关联式容器二
关联式容器二
对set进行插入
插入一个元素,有返回值
1
2
3
4
5
6 pair<iterator, bool> insert(const value_type & value );//参数是const &是因为传入的参数可能是左值也可能是右值
//返回值是一个pair<iterator, bool> 的pair类型,
//插入成功返回对应位置的迭代器,以及true
//插入失败返回阻止插入的迭代器(本来就存在),以及false
set<int> s = {1,2,3,4,5}
pair<set<int>::iterator,bool> res = s.insert(10)插入多个元素,插入多个元素是没有返回值的
1
2
3
4
5
6
7
8
9
10
11
12
13 //第一种形式
set<int> s2 = {2,4,1,4,5,6};
s.insert(s2.begin(),s1.end());
for(auto & ele:nums){
cout << ele << endl;
}
//第二种形式
int arr[5] = {21,213,34,312,3};
s.insert(arr,arr+5);
//第三种形式
s.insert({12,343,4123,4});set用迭代器读元素可以,但是不可以修改
1
2
3 auto it = s.begin();
cout << *it << endl;//可以
*it = 100;//error 不行
map
map的构造和基本操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 void test(){
map<int,string> nums = {
{1,"hello"},
{2,"world"},
{3,"wangdao"}
};
//还可以使用pair
pair<int,string> p2(10,"lll");
map<int,string> nuums2 ={
p2,//这样会有一次复制
pair<int,string>(5,"asd"),//直接用右值也可以
make_pair(6,"asgksdlkg")//用make_pair也可以组织pair
}
}map的遍历
1
2
3
4 for(auto & elem:nums){
//遍历出来的每一个elem都是pair
cout << elem.first <<":" << elem.second<<endl;
}map根据pair的key值去重,map也是根据pair的key升序排列的
1
2
3
4
5
6
7 //迭代器的遍历
map<int,string>::iterator it = nums.begin();
for(: it != nums.end(); ++it){
cout << (*it).first << ":" << (*it).second << endl;
//或者
cout << it->first <<":" << it->second<< endl;
}map的特征
(1)元素唯一:创建map对象时,舍弃了一些元素,key值相同的元素被舍弃,key不同即使value相同也能保留
(2)默认根据key值进行排序
map的查找
1
2
3
4
5
6
7
8
9
10 cout << nums.count(1) << endl;//传入key
auto it = nums.find(1);
if(it != nums.end()){
cout << "存在" << endl;
cout << it->first << ":" << it->second << endl;
}
else{
cout<< "不存在" << endl;
}map的插入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 //map插入单个元素
pair<map<int,string>::iterator,bool> ret = nums.insert(pair<int,string>(7,"alsdlflaksd"));
if(ret.second){
cout << "插入成功 " << endl;
cout << ret.first->first << ":" << ret.first->second << endl;
}else{
cout << "插入失败" << endl;
cout << ret.first->first << ":" << ret.first->second << endl;
}
//插入多个元素
nums.insert({{7,"asdasff"},{8,"qwefdz"},{9,"figoqp"}});
for(auto & elem:nums){
//遍历出来的每一个elem都是pair
cout << elem.first <<":" << elem.second<<endl;
}
map的取下标操作,是把key值作为了下标,可以通过key找到相应的value
1
2
3
4 cout << nums[1] << endl;
//即使访问不存在key不会出错,因为如果访问到不存在的key那么他会自动把这个key和默认的value插入到map里
//并且下标访问是可以进行写操作的
nums[1] = "daowang"
本文是原创文章,采用CC BY-NC-SA 4.0协议,完整转载请注明来自The Yue