一、二分查找算法
lower_bound和upper_bound
用法:
lower_bound(beg,end,key);
返回指向第一个大于等于key值的位置的迭代器或指针,否则返回end
upper_bound(beg,end,key);
返回指向第一个大于key值的位置的迭代器或指针,否则返回end
beg
为容器的起始迭代器或者为数组的首地址end
为容器的结束迭代器或者为数组最后一个元素的下一个位置的地址key
要查找的数据
注意:
- 查找的数组或容器必须是升序排序的
- 使用时需要包含头文件
#include<algorithm>
演练:
int main()
{
vector<int> v{ 2,3,3,4,5,6,6,8,9 };//必须升序排序
vector<int>::iterator x = lower_bound(v.begin(), v.end(), 3);
vector<int>::iterator y = upper_bound(v.begin(), v.end(), 3);
cout << "*x = " << *x << "; *(x+1) = " << *(x + 1) << endl;
cout << "*y = " << *y << "; *(y+1) = " << *(y + 1) << endl;
x = lower_bound(v.begin(), v.end(), 9);
y = upper_bound(v.begin(), v.end(), 10);
cout << "*x = " << *x << endl; //(x+1)=v.end(),越界
cout << "*(y-1) = " << *(y - 1) << endl; //y=v.end(),越界
int a[] = { 1,2,3,4,5,6 };
int* p = lower_bound(a, a + 6, 3);
cout << *p << endl;
}
输出:
*x = 3; *(x+1) = 3
*y = 4; *(y+1) = 5
*x = 9
*(y-1) = 9
*p = 3
二、去重算法
unique
用法:
unique(beg,end);
把重复的元素调到容器或数组尾部,返回第一个重复元素的迭代器或指针
beg
为容器的起始迭代器或者为数组的首地址end
为容器的结束迭代器或者为数组最后一个元素的下一个位置的地址
注意:
- 只能对有序数组或容器使用
- 使用时需要包含头文件
#include<algorithm>
演练:
int main()
{
vector<int> v{ 1,2,2,2,3,3,4,5 };//必须有序,升序降序都可
auto it = unique(v.begin(), v.end());
for (auto i = v.begin(); i != v.end(); ++i) {
if (it == i) cout << "*it=";
cout << *i << " ";
}
cout << endl;
//把后面重复的数删去,彻底去重
v.erase(it, v.end());
for (auto i = v.begin(); i != v.end(); ++i) cout << *i << " ";
//!!!简化步骤,把上面两步合二为一
v.erase(unique(v.begin(), v.end()), v.end());
}
输出:
1 2 3 4 5 *it=3 4 5
1 2 3 4 5
去重记住下面这一句代码就行了:
v.erase(unique(v.begin(), v.end()), v.end());