C++ set insert的返回值

pair<iterator,bool> insert (const value_type& val);

返回布尔对以表示是否发生插入,如果重复插入一个元素会返回false。返回迭代器指向新插入元素。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++ STL库中的set容器是一个用于存储元素的关联容器,它的元素默认按照升序排列,并且保证元素的唯一性。set容器的基本操作包括: 1. 插入元素:使用insert()函数向set容器中插入元素。插入元素的时间复杂度为O(log n)。 ```c++ #include <iostream> #include <set> int main() { std::set<int> s; s.insert(3); s.insert(1); s.insert(4); s.insert(1); // 重复元素不会被插入 s.insert(5); for (auto x : s) { std::cout << x << " "; } std::cout << std::endl; return 0; } ``` 上述代码输出:1 3 4 5 2. 删除元素:使用erase()函数删除set容器中的元素,可以指定要删除的元素值,也可以指定一个迭代器范围。删除元素的时间复杂度为O(log n)。 ```c++ #include <iostream> #include <set> int main() { std::set<int> s{3, 1, 4, 1, 5}; s.erase(1); // 删除元素值为1的元素 for (auto x : s) { std::cout << x << " "; } std::cout << std::endl; return 0; } ``` 上述代码输出:3 4 5 3. 查找元素:使用find()函数和count()函数查找set容器中的元素,find()函数返回一个指向要查找的元素的迭代器,如果元素不存在,则返回end()迭代器。count()函数返回要查找的元素在set容器中出现的次数,因为set容器中的元素保证唯一性,所以count()函数的返回值只能是0或1。查找元素的时间复杂度为O(log n)。 ```c++ #include <iostream> #include <set> int main() { std::set<int> s{3, 1, 4, 1, 5}; auto it = s.find(4); if (it != s.end()) { std::cout << "4 is found" << std::endl; } else { std::cout << "4 is not found" << std::endl; } std::cout << "1 appears " << s.count(1) << " times" << std::endl; std::cout << "2 appears " << s.count(2) << " times" << std::endl; return 0; } ``` 上述代码输出:4 is found,1 appears 1 times,2 appears 0 times。 除了上述基本操作外,set容器还支持迭代器操作和比较操作。更详细的使用方法可以参考C++ STL库的set容器文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值