C++进阶:STL算法4--反转/旋转

1. 简介

函数 作用 文档
reverse(beg,end) 元素重新反序排序。 reverse()
reverse_copy(beg,end,res) reverse()类似,结果写入res reverse_copy()
rotate(beg,mid,end) 元素移到容器末尾,由mid成为容器第一个元素。 rotate()
rotate_copy(beg,mid,end,res) rotate()类似,结果写入res rotate_copy()

2. 示例代码

  • reverse
// reverse algorithm example
#include      // std::cout
#include     // std::reverse
#include        // std::vector

int main () {
  std::vector myvector;

  // set some values:
  for (int i=1; i<10; ++i) myvector.push_back(i);   // 1 2 3 4 5 6 7 8 9

  std::reverse(myvector.begin(),myvector.end());    // 9 8 7 6 5 4 3 2 1

  // print out content:
  std::cout << "myvector contains:";
  for (std::vector::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}
  • reverse_copy
// reverse_copy example
#include      // std::cout
#include     // std::reverse_copy
#include        // std::vector

int main () {
  int myints[] ={1,2,3,4,5,6,7,8,9};
  std::vector myvector;

  myvector.resize(9);    // allocate space

  std::reverse_copy (myints, myints+9, myvector.begin());

  // print out content:
  std::cout << "myvector contains:";
  for (std::vector::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;

  std::cout << '\n';

  return 0;
}
  • rotate
// rotate algorithm example
#include      // std::cout
#include     // std::rotate
#include        // std::vector

int main () {
  std::vector myvector;

  // set some values:
  for (int i=1; i<10; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9

  std::rotate(myvector.begin(),myvector.begin()+3,myvector.end());
                                                  // 4 5 6 7 8 9 1 2 3
  // print out content:
  std::cout << "myvector contains:";
  for (std::vector::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}
  • rotate_copy
// rotate_copy algorithm example
#include      // std::cout
#include     // std::rotate_copy
#include        // std::vector

int main () {
  int myints[] = {10,20,30,40,50,60,70};

  std::vector myvector (7);

  std::rotate_copy(myints,myints+3,myints+7,myvector.begin());

  // print out content:
  std::cout << "myvector contains:";
  for (std::vector::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

3. 练习

  1. 实现函数push_front,能够向vector头部添加数据
template
void push_front(vector & vec,T const& elem);
  1. 实现函数pop_front,能够向vector头部删除数据
template
void pop_front(vector & vec);
  1. 实现函数insert,能够向vector任意位置添加数据
template
void insert(vector & vec,size_t index,T const& elem);
  1. 实现函数erase,能够向vector任意位置删除数据
template
void erase(vector & vec,size_t index);

你可能感兴趣的:(C++进阶:STL算法4--反转/旋转)