程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> C++11新特性應用--介紹幾個新增的便利算法(更改容器中元素順序的算法)

C++11新特性應用--介紹幾個新增的便利算法(更改容器中元素順序的算法)

編輯:C++入門知識

C++11新特性應用--介紹幾個新增的便利算法(更改容器中元素順序的算法)


昨天羅列了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 
  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      // std::cout
#include     // std::copy
#include        // std::vector

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

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

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

    std::cout << '\n';

    std::vector myvector2;
    myvector2.resize(8);
    std::copy_n(myints, -1, myvector2.begin() + 1);
    std::cout << "myvector2 contains:";
    for (std::vector::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 
  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      // std::cout
#include     // std::copy_if, std::distance
#include        // std::vector

int main () {
  std::vector foo = {25,15,5,-5,-15};
  std::vector 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      // std::cout
#include     // std::move (ranges)
#include       // std::move (objects)
#include        // std::vector
#include        // std::string

int main () {
  std::vector foo = {"air","water","fire","earth"};
  std::vector 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 
  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 
  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      // std::cout
#include     // std::shuffle
#include         // std::array
#include        // std::default_random_engine
#include        // std::chrono::system_clock

int main() {
    std::array 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提供的一些便利工具。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved