首页 > 其他分享 >元素排序和去重

元素排序和去重

时间:2023-02-23 22:56:13浏览次数:21  
标签:unique seq int 元素 list Item 排序 data

元素排序和去重

std::list为例
以下讨论基于复杂类型元素,建立表std::list<Item> item_list,如:

class Item
{
public:
	int seq;
	char data[8]
};

struct Item
{
	int seq;
	char data[8]
};

sort:排序

需要元素对象对<进行重载

class Item
{
public:
	bool operator<( const Item & obj ) const
	{
		// 按seq从小到大排序
		return this->seq < obj.seq;
	}
	int seq;
	char data[8];
};

struct Item
{
	bool operator<( const Item & obj ) const
	{
		// 按seq从小到大排序
		return this->seq < obj.seq;
	}
	int seq;
	char data[8];
};
// 对list进行排序
item_list.sort();

unique:去重

需要元素对象重载==

class Item
{
public:
	bool operator<( const Item & obj ) const
	{
		// 按seq从小到大排序
		return this->seq < obj.seq;
	}
	bool operator==( const Item & obj ) const
	{
		return strcmp( this->data, obj.data ) == 0;
	}
	int seq;
	char data[8];
};

结构体类型类似

// 使用unique函数去重
auto unique_iter = unique( item_list.begin(), item_list.end() );

// 删除重复的元素
item_list.erase( unique_iter, unique_iter.end() );

标签:unique,seq,int,元素,list,Item,排序,data
From: https://www.cnblogs.com/tranErmu/p/element_sort_and_unique.html

相关文章