- 前言
- 1.swap()
- 2.reverse()
- 3.sort()
- 4.unique()
- 5.accumulate(first_iterator,last_iterator,求和的初始值)
前言
C++中的algorithm、numeric库中有几个常用的模板函数,以下将其归纳总结一下(swap,reverse,sort,unique,accumulate)。
1.swap()
templatevoid swap ( T& a, T& b ) { T c(a); a=b; b=c; }
上面是swap函数的定义,实际上c就相当于我们平时写的temp临时变量,但实际上该方法并不是一个高效率的方法,因为该函数涉及到了一次复制构造和两次复制,特别是在交换的变量所占空间特别大的时候,最好采用其他方法实现(比如通过异或实现交换)。
举例如下:
#includeusing namespace std; int main() { int n, m; n = 0; m = 1; swap(n, m); cout << n << " " << m << endl; //output: 1 0 return 0; }
使用异或实现两个变量交换,需要注意两个变量不能指向同一个内存空间。
#include2.reverse()using namespace std; int main() { int n, m; n = 0; m = 1; n = n ^ m; m = n ^ m; n = n ^ m; cout << n << " " << m << endl; //output: 1 0 return 0; }
templatevoid reverse (BidirectionalIterator first, BidirectionalIterator last) { while ((first!=last)&&(first!=--last)) { std::iter_swap (first,last); ++first; } }
reverse函数反转[first, last)区间的数据,first和last都是迭代器。
举例如下:
#include#include #include using namespace std; int main() { vector a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; reverse(a.begin(), a.end()); for (int i = 0; i < a.size(); i++) { cout << a[i] << " "; // output: 10 9 8 7 6 5 4 3 2 1 } return 0; }
3.sort()
templatevoid sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
第三个参数comp可不写,不写第三个参数的话默认是升序排列。
如果想要降序排列:
第一种方法是sort之后再使用reverse。
第二种方法是将 greater() 添加到第三个参数中,注意greater函数是在funtional头文件中的,如果你要比较的对象是int,则尖括号中写int,如果不是则写你需要排序的元素的类型。
第三种方法则是自己写比较函数,特别是当你排序的元素是结构体或类的对象。
举例如下:
#include#include #include using namespace std; int main() { vector a = {1, 7, 10, 5, 2, 4, 6, 8, 9, 3}; sort(a.begin(), a.end()); for (int i = 0; i < a.size(); i++) { cout << a[i] << " "; // output: 1 2 3 4 5 6 7 8 9 10 } return 0; }
参数cmp函数实现降序排列。
#include#include #include using namespace std; bool cmp(int a, int b) { return a > b; } int main() { vector a = {1, 7, 10, 5, 2, 4, 6, 8, 9, 3}; sort(a.begin(), a.end(), cmp); for (int i = 0; i < a.size(); i++) { cout << a[i] << " "; // output: 10 9 8 7 6 5 4 3 2 1 } return 0; }
4.unique()
从输入序列中“删除”所有相邻的重复元素,并将这些元素移到最后,返回一个迭代器指针,指针指向的正是最后那些重复元素的第一个元素
5.accumulate(first_iterator,last_iterator,求和的初始值)
对向量元素求和。
templateT accumulate (InputIterator first, InputIterator last, T init) { while (first!=last) { init = init + *first; // or: init=binary_op(init,*first) for the binary_op version ++first; } return init; }
举例如下:
#include#include #include #include using namespace std; int main() { vector a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; cout << accumulate(a.begin(), a.end(), 0) << endl; // output: 55 return 0; }



