现在的位置: 首页 > 综合 > 正文

stl 中 容器 set 类插入,删除,遍历,其中存储的元素为基础类型 int (1)

2019年01月11日 ⁄ 综合 ⁄ 共 962字 ⁄ 字号 评论关闭

集合类型的元素级别简单操作测试

// stlset.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "set"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	//定义存储类型是基本类型int的集合
	set<int> myset;
	
	//批量插入0--9
	pair<set<int>::iterator, bool> Insert_Pair;
	for(int i=0; i<10; i++)
	{
		Insert_Pair = myset.insert(i);
		printf("insert elem=%d into set result=%d\n", i, Insert_Pair.second);
	}

	printf("********************************\n");

	//遍历set
	typedef set<int>::iterator ITERATOR;
	ITERATOR LI;
	for(LI = myset.begin(); LI != myset.end(); LI++)
	{
		printf("output elem=%d\n", (*LI));
	}

	printf("********************************\n");
	//删除其中一个元素方法一:
	for(LI = myset.begin(); LI != myset.end(); LI++)
	{
		if (*LI == 5)
		{
			myset.erase(LI);
			break;
		}
	}

	//遍历set
	for(LI = myset.begin(); LI != myset.end(); LI++)
	{
		printf("output elem=%d\n", (*LI));
	}

	printf("********************************\n");
	//删除其中一个元素方法二:
	LI = myset.find(4);
	if (LI != myset.end())
	{
		myset.erase(LI);
	}
	//遍历set
	for(LI = myset.begin(); LI != myset.end(); LI++)
	{
		printf("output elem=%d\n", (*LI));
	}


	getchar();

	return 0;
}

抱歉!评论已关闭.