Skip to content
Search

Std::vector

lastmod 2021-11-05created 2021-11-052 edits

vector is the most frequently used part of the STL. The data structure used most often in programming is the array. vector can be used in place of arrays. Because vector has much in common with arrays, it is the easiest STL container to understand, and it is also easy to know where to use it. Those who read the earlier article in this series on list (or who already know it) will find that vector is used in many similar ways, so I expect they will understand it much faster than list. Some points already covered for list are not repeated here, so if you have not read the article on list, please be sure to read it.

How to implement a 2D array

Reference: http://neodreamer.tistory.com/19 Declare it as follows.

vector < vector < int > > vcArray;

To initialize it, use a for loop as follows.

for ( int i = 0 ; i < ROW; ++i ) { // 주어진 ROW 만큼 반복
    vector<int> elem; // vector 를 생성하고
    elem.resize(COL); // 원하는 COL 크기로 할당
    vcArray.push_back(elem); // 배열에 추가
}

Clear the COL data in each ROW, then finally clear the ROW data.

for (int row = 0; row < (int)vcArray.size(); ++row)
    vcArray[row].clear();
vcArray.clear(); 

Use it as follows.

int temp = vcArray[1][2]; 
vcArray[1][2] = 3;

How to pass a vector to an existing C API

This is how to turn a vector into a pointer-type array.

To pass a pointer to the data, use the following.

vector<int> v;
&v[0]

According to the C++ standard, the data elements in a vector must be stored in contiguous memory. In other words, it is the same as an array.

if ( !v.empty() ) {
    // 빈 벡터일 때 v.size()가 0인 상황에서 &v[0]은 존재하지 않은 메모리의 주소값을 만드려고 하니 결국 오작동을 일으키게 된다.
    // 따라서 v.empty()로 빈 벡터인지를 검사할 필요가 있다.
    doSomething( &v[0], v.size() );
}

Note that, depending on the compiler, you may see a compiler warning telling you to use v.begin() instead of &v[0]. If you really want to use v.begin(), write &*v.begin().

See also

Favorite site

References


  1. About_stl-cpp_stl_programming.pdf ↩

author Zer0 sitemap