STL中transform ,erase,sort,unique的使用

1.transform用来改变集合中所有的元素,按照统一的标准。

2.在集合中删除相同的元素:sort,unique, erase。


#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

int thriceNumber(int x)
{
	return 3*x;
}
int main()
{
	
	vector<int> vt;
	
	vt.push_back(5);
	vt.push_back(10);
	vt.push_back(4);
	vt.push_back(3);

	transform(vt.begin(),vt.end(),vt.begin(),thriceNumber);

	for (vector<int>::iterator it  = vt.begin(); it != vt.end(); ++it)
	{
		cout<<*it<<endl;
	}
	cin.get();
	cin.get();
	return 0;
}

int main2()
{

	//去除string中重复元素的步骤
	string str = "woaini";
	//1.排序 sort
	sort(str.begin(),str.end());
	//2.去除重复的元素,此时主要得到返回的iterator
	string::iterator iter = unique(str.begin(),str.end());
	//3.删除后面重复的元素
	str.erase(iter,str.end());

	cout<<str.c_str() <<endl;

	cin.get();
	cin.get();
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++ STL sortunique 函数都是算法函数,用于对指定范围内的元素进行排序和去重。 sort 函数用于对指定范围内的元素进行升序排列,默认使用 operator< 进行比较。sort 函数的定义如下: ```c++ template<class RandomAccessIterator> void sort(RandomAccessIterator first, RandomAccessIterator last); template<class RandomAccessIterator, class Compare> void sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp); ``` 其,first 和 last 分别表示要排序的元素范围的起始和终止位置,包括起始位置但不包括终止位置。如果要排序的元素是一个数组,可以使用数组名和数组名加上元素个数来表示起始和终止位置。 sort 函数的第二个参数 comp 是一个可选的比较函数,用于自定义元素之间的大小关系。如果不指定比较函数,则默认使用 operator<。比较函数需要满足严格弱序关系,即满足: 1. 自反性:对于所有的 x,都有 x <= x。 2. 反对称性:对于所有的 x 和 y,如果 x < y,则 y > x。 3. 传递性:对于所有的 x、y 和 z,如果 x < y 且 y < z,则 x < z。 4. 可比较性:元素之间必须可以进行比较。 unique 函数用于去重,可以将指定范围内相邻的重复元素保留一个,并返回去重后的数组末尾的迭代器。unique 函数的定义如下: ```c++ template<class ForwardIterator> ForwardIterator unique(ForwardIterator first, ForwardIterator last); template<class ForwardIterator, class BinaryPredicate> ForwardIterator unique(ForwardIterator first, ForwardIterator last, BinaryPredicate pred); ``` 其,first 和 last 分别表示要去重的元素范围的起始和终止位置,包括起始位置但不包括终止位置。unique 函数的第二个参数 pred 是一个可选的二元谓词函数,用于自定义元素之间的相等关系。如果不指定二元谓词函数,则默认使用 operator==。二元谓词函数需要满足等价关系,即满足: 1. 自反性:对于所有的 x,都有 pred(x, x) = true。 2. 对称性:对于所有的 x 和 y,有 pred(x, y) = pred(y, x)。 3. 传递性:对于所有的 x、y 和 z,如果 pred(x, y) 且 pred(y, z),则 pred(x, z)。 需要注意的是,unique 函数并不会改变数组的大小,只是将重复元素移到了数组的末尾,并返回去重后的数组末尾的迭代器。因此,去重后的元素个数可以通过数组的起始地址和返回值的差来计算。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值