본문 바로가기

Algorithm/TIP

[C++] 2차원 벡터 초기화

728x90

 

2차원 벡터를 초기화 하는 방법

 

라이브러리

#include <vector>

 

 

 

둘다 미리 할당해 두고 값만 넣는 방법 
vector<vector<int>> v;

int main() {

    cin >> N;
    v.assign(N, vector<int>(N, 0));


    for (int j = 0; j < N; j++) {
        for (int i = 0; i < N; i++) {
            cin >> v[j][i];
        }
    }

}

이거를 쓰자 

 

 

2차원 벡터에 pushback으로 1차원벡터를 넣기
vector<vector<int>> v;

int main() {

    cin >> N;
    vector<int> vec(N, 0);


    for (int j = 0; j < N; j++) {
        for (int i = 0; i < N; i++) {
            cin >> vec[i];
        }
        v.push_back(vec);
        vec.assign(N, 0);
    }

}

 

 

모두 pushback으로 넣기
vector<vector<int>> v;

int main() {

    cin >> N;
    vector<int> vec(N, 0);


    for (int j = 0; j < N; j++) {
        for (int i = 0; i < N; i++) {
            cin >> num;
            vec.push_back(num);
        }
        v.push_back(vec);
        vec.clear(); 
    }

}

 

 

 

Push back이 느린가?

https://stackoverflow.com/questions/20168051/why-push-back-is-slower-than-operator-for-a-previously-allocated-vector

 

Why push_back is slower than operator[] for a previously allocated vector

I just read this blog http://lemire.me/blog/archives/2012/06/20/do-not-waste-time-with-stl-vectors/ comparing performance of operator[] assignment and push_back on memory pre-reserved std::vector a...

stackoverflow.com

 

728x90