首页 > 编程语言 > 详细

C++11新特性应用--介绍几个新增的便利算法(更改容器中元素顺序的算法)

时间:2016-01-18 22:53:08      阅读:364      评论:0      收藏:0      [点我收藏+]

昨天罗列了C++11中新增的几个算法,包括 find_if_not、all_of、any_of、none_of四个算法,这四个算法的共同点就是Non-modifying sequence operations。

所以,今天就来八一八C++11中新增的算法,而这些算法的特点是:Modifying sequence operations。

copy算法我们很熟悉,这里介绍一下C++11新增的copy_n。

copy_n
原型:

template <class InputIterator, class Size, class OutputIterator>
  OutputIterator copy_n (InputIterator first, Size n, OutputIterator result);

作用:
Copies the first n elements from the range beginning at first into the range beginning at result.

返回值很关键:
The function returns an iterator to the end of the destination range (which points to one past the last element copied).

如果n为负数的时候:
If n is negative, the function does nothing.

如果两个区间有重复的时候:
If the ranges overlap, some of the elements in the range pointed by result may have undefined but valid values.

应用:

#include <iostream>     // std::cout
#include <algorithm>    // std::copy
#include <vector>       // std::vector

int main() {
    int myints[] = { 10,20,30,40,50,60,70 };
    std::vector<int> myvector;
    myvector.resize(8);   // allocate space for 7 elements

    std::copy_n(myints, 7, myvector.begin()+1);

    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
        std::cout << ‘ ‘ << *it;

    std::cout << ‘\n‘;

    std::vector<int> myvector2;
    myvector2.resize(8);
    std::copy_n(myints, -1, myvector2.begin() + 1);
    std::cout << "myvector2 contains:";
    for (std::vector<int>::iterator it = myvector2.begin(); it != myvector2.end(); ++it)
        std::cout << ‘ ‘ << *it;

    std::cout << ‘\n‘;
    return 0;
}
//输出:
myvector contains : 0 10 20 30 40 50 60 70
myvector2 contains : 0 0 0 0 0 0 0 0

copy_if
原型:

template <class InputIterator, class OutputIterator, class UnaryPredicate>
  OutputIterator copy_if (InputIterator first, InputIterator last,
                          OutputIterator result, UnaryPredicate pred);

作用:
Copies the elements in the range [first,last) for which pred returns true to the range beginning at result.

应用:

#include <iostream>     // std::cout
#include <algorithm>    // std::copy_if, std::distance
#include <vector>       // std::vector

int main () {
  std::vector<int> foo = {25,15,5,-5,-15};
  std::vector<int> bar (foo.size());

  // copy only positive numbers:
  auto it = std::copy_if (foo.begin(), foo.end(), bar.begin(), [](int i){return !(i<0);} );
  bar.resize(std::distance(bar.begin(),it));  // shrink container to new size

  std::cout << "bar contains:";
  for (int& x: bar) std::cout << ‘ ‘ << x;
  std::cout << ‘\n‘;

  return 0;
}

move和move_backward
move算得上是老生常谈了,但需要注意的是:
The value of the elements in the [first,last) is transferred to the elements pointed by result. After the call, the elements in the range [first,last) are left in an unspecified but valid state.

直接给例子代码:

#include <iostream>     // std::cout
#include <algorithm>    // std::move (ranges)
#include <utility>      // std::move (objects)
#include <vector>       // std::vector
#include <string>       // std::string

int main () {
  std::vector<std::string> foo = {"air","water","fire","earth"};
  std::vector<std::string> bar (4);

  // moving ranges:
  std::cout << "Moving ranges...\n";
  std::move ( foo.begin(), foo.begin()+4, bar.begin() );

  std::cout << "foo contains " << foo.size() << " elements:";
  std::cout << " (each in an unspecified but valid state)";
  std::cout << ‘\n‘;

  std::cout << "bar contains " << bar.size() << " elements:";
  for (std::string& x: bar) std::cout << " [" << x << "]";
  std::cout << ‘\n‘;

  // moving container:
  std::cout << "Moving container...\n";
  foo = std::move (bar);

  std::cout << "foo contains " << foo.size() << " elements:";
  for (std::string& x: foo) std::cout << " [" << x << "]";
  std::cout << ‘\n‘;

  std::cout << "bar is in an unspecified but valid state";
  std::cout << ‘\n‘;

  return 0;
}
//输出:
Moving ranges...
foo contains 4 elements: (each in an unspecified but valid state)
bar contains 4 elements: [air] [water] [fire] [earth]
Moving container...
foo contains 4 elements: [air] [water] [fire] [earth]
bar is in an unspecified but valid state

下面说说move_backward:
原型:

template <class BidirectionalIterator1, class BidirectionalIterator2>
  BidirectionalIterator2 move_backward (BidirectionalIterator1 first,
                                        BidirectionalIterator1 last,
                                        BidirectionalIterator2 result);

作用:
Moves the elements in the range [first,last) starting from the end into the range terminating at result.

The function returns an iterator to the first element in the destination range.

The function begins by moving (last-1) into (result-1), and then follows backward by the elements preceding these, until first is reached (and including it).

还没搞懂应用,C++ Reference上的例子在VS2015下不能运行,等下有时候再搞搞。

shuffle
shuffle有 改组 的意思。
原型:

template <class RandomAccessIterator, class URNG>
  void shuffle (RandomAccessIterator first, RandomAccessIterator last, URNG&& g)

作用:
Rearranges the elements in the range [first,last) randomly, using g as uniform random number generator.

应用:

#include <iostream>     // std::cout
#include <algorithm>    // std::shuffle
#include <array>        // std::array
#include <random>       // std::default_random_engine
#include <chrono>       // std::chrono::system_clock

int main() {
    std::array<int, 5> foo{ 1,2,3,4,5 };

    // obtain a time-based seed:
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();

    shuffle(foo.begin(), foo.end(), std::default_random_engine(seed));

    std::cout << "shuffled elements:";
    for (int& x : foo) std::cout << ‘ ‘ << x;
    std::cout << ‘\n‘;

    return 0;
}
//输出
//shuffled elements: 4 2 1 3 5

上面的代码中用到了头文件chrono,在之前的博客中有讲诉过,也算是C++11提供的一些便利工具。

C++11新特性应用--介绍几个新增的便利算法(更改容器中元素顺序的算法)

原文:http://blog.csdn.net/wangshubo1989/article/details/50539268

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!