fill算法用来填充容器,当然创建容器的时候,也可以达到与fill算法一样的效果.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//fill算法的手动实现.
template <typename T, typename V>
void myFill(T first, T last, const V value)
{
while (first != last)
{
*first++ = value;
}
}
int main()
{
vector<int> s = {1,2,3,4,5,6,7};
//用来让指定范围内的元素填充为5.
fill(s.begin(), s.begin() + 3, 5); // 5 5 5 4 5 6 7
//当然这样也是可以的.给容器temp填充了10个5.
vector<int> temp(10,5);
system("pause");
return 0;
}
rotate用来循环容器内的元素.但它和swap_ranges不同,它旋转的元素个数不用相等.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//rotate的实现.
template <typename T>
void myRotate(T first, T mid, T last)
{
//这个实现挺有趣的,倒序即可实现.
reverse(first, mid);
reverse(mid, last);
reverse(first, last);
}
int main()
{
vector<int> s = {1,2,3,4,5,6,7};
rotate(s.begin(), s.begin() + 3, s.end()); // 4 5 6 7 1 2 3
system("pause");
return 0;
}
既然有rotate,那么肯定有rotate_copy了.
template <typename T>
void myRotate_copy(T first, T mid, T last, T new_first)
{
//一般有copy的算法,都比较简单实现.
T temp = mid;
while (temp != last)
{
*new_first = *temp++;
}
while (first != mid)
{
*new_first = *first++;
}
}