C++常用算法库函数记录
1.std::copy
常用语法:
copy([inputIt] first, [inputIt] last, [destinationIt] d_first);
-
将[first, last)范围内的元素复制到起始为d_first的另一范围,它们均为迭代器
-
返回值:指向目标范围中最后复制元素的下个元素的迭代器
例:
vector<int> a = {1, 1, 1, 1, 1};
vector<int> b = {0, 0, 0};
copy(b.begin(), b.end(), a.begin() + 1);
上述代码运行后,a输出为{1, 0, 0, 0, 1}
注意:copy函数不会分配新的空间,比如copy(a.begin(), a.end(), b.begin())
是错误的,因为b那一块只分配了三个int的空间,而需要复制的个数有五个
2.std::sort
常用语法:
sort([Iter] first, [Iter]last, [Compare, Optional] comp);
- 排序[first, last)范围内的元素,排序依据是comp(可选),若未指定comp则默认是非降序排序。此排序不具有稳定性。
- 无返回值
- comp的形式可以是:
bool cmp (const Type1 &a, const Type2 &b);
- 还可以用lambda表达式来写cmp
例:
bool cmp (int a, int b)
{
reurn a > b; //升序
}
vector <int> v = {1, 5, 3, 9, 2};
sort(v.begin(), v.end(), cmp);
sort
(
v.begin(),
v.end(),
[](int a, int b)
{
return a < b;
}
);
分别输出为{9, 5, 3, 2, 1}
和 {1, 2, 3, 5, 9}