unique函数
删除连续重复的范围
template <class ForwardIterator>
ForwardIterator unique ( ForwardIterator first, ForwardIterator last );
template <class ForwardIterator, class BinaryPredicate>
ForwardIterator unique ( ForwardIterator first, ForwardIterator last, BinaryPredicate pred );
返回值,返回的是迭代器,指向新的末端
测试
// unique algorithm example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool myfunction (int i, int j) {
return (i==j);
}
int main () {
int myints[] = {10,20,20,20,30,30,20,20,10}; // 10 20 20 20 30 30 20 20 10
vector<int> myvector (myints,myints+9);
vector<int>::iterator it;
// using default comparison:
it = unique (myvector.begin(), myvector.end()); // 10 20 30 20 10 ? ? ? ?
// ^
myvector.resize( it - myvector.begin() ); // 10 20 30 20 10
// using predicate comparison:
unique (myvector.begin(), myvector.end(), myfunction); // (no changes)
// print out content:
cout << "myvector contains:";
for (it=myvector.begin(); it!=myvector.end(); ++it)
cout << " " << *it;
cout << endl;
return 0;
}
sort函数
注:参数必须是RandomAccessIterator类型的迭代器,即:只有vector,string,array,deque类型,可以用sort。
参数:区间是左闭右开的。默认是从小到大排序
template <class RandomAccessIterator>
void sort ( RandomAccessIterator first, RandomAccessIterator last );
template <class RandomAccessIterator, class Compare>
void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );
测试
// sort algorithm example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool myfunction (int i,int j) { return (i<j); }
struct myclass {
bool operator() (int i,int j) { return (i<j);}
} myobject;
int main () {
int myints[] = {32,71,12,45,26,80,53,33};
vector<int> myvector (myints, myints+8); // 32 71 12 45 26 80 53 33
vector<int>::iterator it;
// using default comparison (operator <):
sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33
// using function as comp
sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)
// using object as comp
sort (myvector.begin(), myvector.end(), myobject); //(12 26 32 33 45 53 71 80)
// print out content:
cout << "myvector contains:";
for (it=myvector.begin(); it!=myvector.end(); ++it)
cout << " " << *it;
cout << endl;
//myvector contains: 12 26 32 33 45 53 71 80
return 0;
}