set 跟 map 容器很像,但它俩又有很大的不同,它们的底层实现都是树,元素都是有序的,但map是可以修改元素的,而 set 就不行了,set 里的元素只有删除的情况,没有修改的情况;所以发现没有? set 是没有 operator[] 操作的。
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <set>
int main ()
{
std::set<int> myset;
std::set<int>::iterator it;
std::pair<std::set<int>::iterator,bool> ret;
// set some initial values:
for (int i = 1; i <= 5; ++i)
{
// set: 10 20 30 40 50
myset.insert(i*10);
}
ret = myset.insert(20); // no new element inserted
if (!ret.second)
{
it = ret.first; // "it" now points to element 20
std::cout << "insert failed!\n" << *it << "\n";
}
myset.insert(it, 25); // max efficiency inserting
myset.insert(it, 24); // max efficiency inserting
myset.insert(it, 26); // no max efficiency inserting
int myints[

博客介绍了C++中set和map容器的区别。二者底层实现都是树,元素有序,但map可修改元素,set只能删除不能修改,且set没有operator[]操作。若元素为自定义类型,set和map都需实现operator <。
最低0.47元/天 解锁文章
3669

被折叠的 条评论
为什么被折叠?



