c++篇
reverse(作用翻转)
#include <iostream>
#include <algorithm> // 包含 reverse 函数
#include<vector>
using namespace std;
int main()
{
vector<int > a({1, 2, 3, 4, 5});
reverse(a.begin(), a.end());
for (int x : a)
cout << x << endl; //
return 0;
}
输出为以下内容。
5
4
3
2
1
注意begin()与end()里面是不能填任何东西的,如果想要修改一个范围内的,可以按以下的方式来。
reverse(a.begin()+x1,a.begin()+x2)
其中x1,x2代表下标的数字,这样就是翻转x1~x2这个范围内的数字,x2这个数字的下标取不到。
#include <iostream>
#include <algorithm> // 包含 reverse 函数
using namespace std;
int main()
{
int a[5] = {1, 2, 3, 4, 5};
reverse(a, a + 3); // 第一个位置为需要翻转的数组和翻转该数组所需要的下标,而第二个位置是取不到的。
for (int x : a)
cout << x << endl; // 修正为 endl
return 0;
}
输出为以下内容:
3
2
1
4
5
unique(作用去重)
unique函数一定要保证相同元素挨在一起。
#include <iostream>
#include <algorithm> // 包含了unique函数
using namespace std;
int main()
{
int a[]={1,1,2,2,3,5} ;
int n=unique(a,a+sizeof(a) / sizeof(a[0]))-a; // sizeof(a)/sizeof(a[0])来获取数组长度。
//n 是一个指向数组末尾下一个位置的指针,而 a 是指向数组起始位置的指针,所以 n- a 就是去重后数组的长度
for (int i=0;i<n;i++)
cout<<a[i]<<endl;
return 0;
}
返回内容如下
1
2
3
5
就像我们上文所说重复数字必须相邻排列如果不相邻呢?把数组a重新设置一下。
int a[]={1,2,1,2,2,3,5}
返回内容如下,就没有去除重复没有排列在一起的数字了,所以我们使用前可以先进行排序。
1
2
1
2
3
5
以下是vector的写法。
#include <iostream>
#include <algorithm>
#include<vector>
using namespace std;
int main()
{
vector<int> a{{1,1,3,5,5,7}} ;
int n=unique(a.begin(),a.end())-a.begin();
for (int i=0;i<n;i++)
cout<<a[i]<<endl;
return 0;
}
同理(a.begin()+x1,a.end()+x2)也可以弄向去重的范围。
当然还有一个其他的常用写法,用上一个earse,。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> a{{1,1,3,5,5,7}} ;
a.erase(unique(a.begin(),a.end()),a.end());
for (int x:a)
cout<<x<<" ";
return 0;
}
输出为:
1 3 5 7