CS/C++

[Mastering C++ Programming] - Vector

sliver__ 2022. 12. 4. 11:10
728x90
  • runtime에 size가 늘어나거나 줄어들 수 있다.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main () {
  vector<int> v = { 1, 5, 2, 4, 3 };

  cout << "\nSize of vector is " << v.size() << endl;

  auto pos = v.begin();

  cout << "\nPrint vector elements before sorting" << endl;
  while ( pos != v.end() )
    cout << *pos++ << "\t";
  cout << endl;

  sort( v.begin(), v.end() );

  pos = v.begin();

  cout << "\nPrint vector elements after sorting" << endl;

  while ( pos != v.end() )
    cout << *pos++ << "\t";
  cout << endl;

  return 0;
}

 

  • 결과는 아래와 같다.
./a.out

Size of vector is 5

Print vector elements before sorting
1	5	2	4	3

Print vector elements after sorting
1	2	3	4	5

 

  • API는 아래와 같다.

 

 

  • isstream_iterator 와 osstream_iterator를 사용하여 vector로 copy 및 출력이 가능하다.
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;

int main () {
    vector<int> v;

    cout << "\nType empty string to end the input once you are done feeding the vector" << endl;
    cout << "\nEnter some numbers to feed the vector ..." << endl;
   

    istream_iterator<int> start_input(cin);
    istream_iterator<int> end_input;

    copy ( start_input, end_input, back_inserter( v ) );


    cout << "\nPrint the vector ..." << endl;
    copy ( v.begin(), v.end(), ostream_iterator<int>(cout, "\t") );
    cout << endl;

 
    return 0;
}

 

 

+++)

  • 벡터는 dynamic하게 size를 지원한다.
  • 하지만 실제로 size가 커지게되면 연속적으로 데이터를 유지하기 위해 새로운 공간에 data를 copy하고 새로운 데이터를 추가하는 과정이 생긴다.
  • 그러므로 실제로는 다른 STL container가 더 도움이 될 수 있다.
728x90