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

ACE 容器之五 ACE_Bounded_Set 和 ACE_Unbounded_Set 的使用

2019年01月10日 ⁄ 综合 ⁄ 共 1915字 ⁄ 字号 评论关闭

这两个类是ACE提供的集合容器类。集合容器类也分为有边界和无边界之分。

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

#include "stdafx.h"
#include "ace/OS_Memory.h"
#include "ace/Log_Msg.h"
#include "ace/Containers.h"

//有限制大小的集合
int runBoundedSet()
{
	ACE_TRACE ("SetExample::runBoundedSet");
	ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Using a bounded set\n")));

	ACE_Bounded_Set<int> bset(10);

	//插入连词,验证集合的性质,同一个集合中插入两个相同的元素会失败
	int elem[10];
	for (int i = 0; i < 10; i++)
	{
		elem[i] = i;
		//Inserting two copies of the same element isn't allowed.
		bset.insert (elem[i]);


		if (bset.insert(elem[i]) == 1)
		{
			ACE_DEBUG ((LM_INFO, ACE_TEXT("insert elements %d existed in set\n"), elem[i]));
		}
	}

	//查找元素 5 和 8
	int  elem1 = 5;
	int  elem2 = 8;
	if (!bset.find (elem1) && !bset.find (elem2))
	{
		ACE_DEBUG ((LM_INFO, ACE_TEXT ("The elements %d and %d are ") ACE_TEXT ("in the set!\n"), elem1, elem2));
	}

	//删除前边5个原色
	for (int j = 0; j < 5; j++)
	{
		bset.remove (elem[j]);  // Remove the element from the set.
		ACE_DEBUG((LM_DEBUG, ACE_TEXT ("%d "), elem[j]));
	}
	printf("\n---------------------------\n");

	//然后再查找 0 和 49
	if ((bset.find (elem[0]) == -1) && (bset.find (elem[4]) == -1))
	{
		ACE_DEBUG ((LM_INFO, ACE_TEXT ("The elements %d and %d are ") ACE_TEXT ("NOT in the set!\n"), elem[0], elem[4]));
	}

	return 0;
}



//没有限制集合大小类型的集合,并且元素是指针
int runUnboundedSet ()
{
	ACE_TRACE ("SetExample::runUnboundedSet");
	ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Using an unbounded set.\n")));

	int *a = NULL;
	int *b = NULL;

	ACE_Unbounded_Set<int*> uset;
	for (int m = 0; m < 10; m++)
	{
		int *elem = new int;
		//特殊记录一下指针的值,为了查找。
		if (m == 0)
		{
			a = elem;
		}
		else if(m==9)
		{
			b = elem;
		}
		*elem = m;
		uset.insert (elem);
	}

	//查找的时候一定注意这块,内存匹配查找,否则要自己实现查找函数
	//验证元素是否在集合
	if (!uset.find(a) && !uset.find(b))
	{
		ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Found the elements\n")));
	}


	// Iterate and destroy the elements in the set.
	ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Deleting the elements\n")));

	//遍历
	ACE_Unbounded_Set_Iterator<int*> iter (uset);
	for (iter = uset.begin (); iter != uset.end (); iter++)
	{
		int* elem = (*iter);
		printf("%d ", *elem);
		delete elem;
	}
	printf("\n-------------------------------------\n");
	return 0;
}


int _tmain(int argc, _TCHAR* argv[])
{
	runBoundedSet();
	runUnboundedSet();
	getchar();
	return 0;
}

抱歉!评论已关闭.