stl set 的 insert()

        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[] = {5, 10, 15};              // 10 already in set, not inserted, 5 and 15 insert success
	myset.insert(myints, myints + 3);


	for (it = myset.begin(); it != myset.end(); ++it)
	{	
		std::cout << ' ' << *it;
	}
	std::cout << '\n';

	myset.erase(50);
	for (it = myset.begin(); it != myset.end(); ++it)
	{	
		std::cout << ' ' << *it;
	}
	std::cout << '\n';
	
	return 0;
}

因为 set 里的元素是有序的,所以跟 map 一样,如果元素是自定义类型的,必须实现 operator <

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <set>

struct objectKey
{
	int ldp_oidx;
	int lsp_oidx;
	bool operator<(const objectKey &key) const
	{
		return ldp_oidx > key.ldp_oidx;
	}
};

int main ()
{

	std::set<objectKey> objSet;
	std::set<objectKey>::iterator itKey;
	
	objectKey key = {0, 1};
	objectKey key2 = {1, 2};
	objectKey key3 = {2, 3};
	objSet.insert(key);
	objSet.insert(key2);
	objSet.insert(key3);
	
	for(itKey = objSet.begin(); itKey != objSet.end(); ++itKey)
	{
		printf("%d, %d\n", (*itKey).ldp_oidx, (*itKey).lsp_oidx);
	}
	
	
	return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值