1. 使用 insert 插入时的返回值:
将一个元素插入 (insert) 到 set 或 multiset 中时,如果插入失败返回的类型是一个 pair 的自定类型,insert 源码如下:
insert 的重载方式目前有8种,本篇说明的是
1 template <bool _Multi2 = _Multi, enable_if_t<!_Multi2, int> = 0> 2 pair<iterator, bool> insert(const value_type& _Val) 3 { 4 const auto _Result = _Emplace(_Val); 5 return {iterator(_Result.first, _Get_scary()), _Result.second}; 6 }
可以从上边第2行看到,pair模板他返回的一个是迭代器,一个是 bool 类型。返回的迭代器保存在 pair.first 中(注意,他是个地址),是 pair 里面的第一个值,是T1类型;pair.second(bool 类型) 是 pair 里面的第二个值,是T2类型,如下代码,由于 setInt 已经存在元素5,再次插入5必然会失败:
1 #include <iostream> 2 #include <set> 3 4 using namespace std; 5 6 int main() 7 { 8 set<int> setInt; 9 10 for (int i = 0; i < 2; i++) 11 { 12 setInt.insert(i); 13 } 14 15 for (int i = 0; i < 4; i++) 16 { 17 //bool ret = setInt.insert(i); //返回值不光是一个 bool 类型,这样写是会报错的 18 pair<set<int>::iterator, bool> ret = setInt.insert(i); //返回的是一个 pair<set<int>::iterator, bool> 19 20 cout << "从迭代器获取插入的元素:" << *(ret.first) << endl; 21 cout << "用 ret.second 返回bool:" << ret.second << endl; 22 23 if (ret.second) 24 { 25 cout << "插入" << i << "成功" << endl; 26 } 27 else 28 { 29 cout << "插入" << i << "失败" << endl; 30 } 31 cout << endl; 32 } 33 34 return 0; 35 }
打印结果:
pair<T1,T2> 用来存放的两个值的类型,可以不一样,也可以一样,如T1为 int,T2为 float。T1,T2也可以是自定义类。
==================================================================================================================================
STL——容器(Set & multiset) insert 的返回值 和 pair 的用法
原文:https://www.cnblogs.com/CooCoChoco/p/13058316.html