2014年7月10日 星期四

存取指定vector索引值變數 ( Assigns a Element in the vector ) < C++ std::vector::at >



/*
(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>

struct STRUCT
{
    int number;
    std::string str;
};

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

void printStruct(STRUCT& s) {
    std::cout<< s.number <<" : "<< s.str <<std::endl;
}

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

  for( unsigned i = 0; i < first.size(); i++ )
      first.at(i) = i;

  for( unsigned i = 0; i < second.size(); i++ ){
      second.at(i).number = i;
      second.at(i).str = "string";
  }

  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(), printStruct);

  return 0;
}

編譯結果如下:

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

0 意見:

張貼留言