std::unique_copy 用法

描述:
       拷贝容器中无连续相同的元素到另一容器中。
       用 operator== 比较元素。
       可以通过先调用std::sort函数,再调用std::unique_copy函数,实现移除重复元素功能。

定义:

template< class InputIt, class OutputIt >
OutputIt unique_copy( InputIt first, InputIt last,
                      OutputIt d_first );

template< class InputIt, class OutputIt >
constexpr OutputIt unique_copy( InputIt first, InputIt last,
                                OutputIt d_first );
template< class InputIt, class OutputIt, class BinaryPredicate >
OutputIt unique_copy( InputIt first, InputIt last,
                      OutputIt d_first, BinaryPredicate p );

template< class InputIt, class OutputIt, class BinaryPredicate >
constexpr OutputIt unique_copy( InputIt first, InputIt last,
                                OutputIt d_first, BinaryPredicate p );

参数:
       first - 源容器的起始范围迭代器
       last - 源容器的终止范围迭代器
       p - 若元素应被当做相等则返回 ​true 的二元谓词。

返回值:
       返回最后被写入元素后一元素的输出迭代器。

示例:

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>

int main()
{
	std::string s1 = "The      string    with mmany       sspaces!";

	std::string s2, s3;
	std::unique_copy(s1.begin(), s1.end(), std::back_inserter(s2));
	std::cout << s2 << std::endl;//The string with many spaces!
}
#include <iostream>
#include <algorithm>
#include <vector>

struct SData
{
	int m_nData;
	double m_dData;

	SData(int nData, double dData)
		:m_nData(nData),m_dData(dData)
	{
	}
};

int main()
{
	std::vector<SData> v;
	for (int i = 0; i < 5; i++)
	{
		SData data(i,i);
		v.push_back(data);
		v.push_back(data);
	}
	std::vector<SData> v2;

	//使用lambda表达式指定条件(一般用于自定义元素)
	auto iter = std::unique_copy(v.begin(), v.end(), std::back_inserter(v2), [](const SData& data1,const SData& data2)
	{
		return data1.m_nData == data2.m_nData;
	});

	for (int i = 0; i < v2.size(); i++)
		std::cout << v2[i].m_nData << " ";
	std::cout << std::endl;
	//0 1 2 3 4

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值