2014年7月10日 星期四

分配或取代vector內容 ( Assigns or Replacing Content to Vector) < C++ std::vector::assign >



/* 
(C) Marc Talk 2014 http://ccw1986.blogspot.tw/
Compiler environment : MinGW 4.8.2/ QT Creator 3.2 / Window 7
Release              : 2014/07/10
*/

#include <iostream>
#include <vector>
#include <algorithm>

void printElem(int& elem) {
    std::cout<< elem <<std::endl;
}

int main ()
{
  std::vector<int> first;
  std::vector<int> second;
  std::vector<int> third;

  //宣告7個int變數都是10
  first.assign( 7, 100 );

  //給予first中1~5的int變數
  std::vector<int>::iterator it_begin;
  std::vector<int>::iterator it_end;
  it_begin  = first.begin()+1;
  it_end    = first.end()-1;
  second.assign ( it_begin, it_end );

  //給予array中的前4個int變數
  int array[] = {10, 20, 30, 40, 50};
  third.assign( array, array+4 );

  std::cout << "Size of first: " << int (first.size()) << '\n';
  for_each(first.begin(), first.end(), printElem);

  std::cout << "Size of second: " << int (second.size()) << '\n';
  for_each(second.begin(), second.end(), printElem);

  std::cout << "Size of third: " << int (third.size()) << '\n';
  for_each(third.begin(), third.end(), printElem);

  return 0;
}

編譯結果如下:


參考來源:http://www.cplusplus.com/reference/vector/vector/assign/

0 意見:

張貼留言