본문 바로가기
공부/코딩 개념정리

[C++] 1차원, 2차원 벡터 초기화 (1D 2D vector initialization)

by 소소하지만유니크한 2021. 3. 17.
728x90

 

 

c++를 사용하다보면 sort() 등 지원을 해주기 때문에 vector 형태로 사용하는 경우가 많은데, vector 형태의 데이터를 초기화하는 다양한 방법들을 소개하도록 하겠습니다.

1D vector 초기화

아래의 포스팅을 참고하여 1차원 vector 초기화하는 방법 6가지를 정리하였습니다.

www.geeksforgeeks.org/initialize-a-vector-in-cpp-different-ways/

 

Initialize a vector in C++ (6 different ways) - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

1. 값을 push하며 초기화 

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    // Create an empty vector
    vector<int> vect;
 
    vect.push_back(10);
    vect.push_back(20);
    vect.push_back(30);
 
    for (int x : vect)
        cout << x << " ";
 
    return 0;
}

1D의 경우는 가장 쉽게 빈 vector를 생성하고 원하는 값을 push_back()을 이용하여 값을 추가할 수 있습니다. 해당 코드를 이용하여 크기와 값에 대한 제한없이 자유롭게 값을 추가할 수 있습니다. 

 

output

10 20 30

 

2.  특정 크기의 vector를 같은 값으로 초기화

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    int n = 3;
 
    vector<int> vect(n, 10);
 
    for (int x : vect)
        cout << x << " ";
 
    return 0;
}

해당 코드는 vector의 크기와 채워 넣을 값이 정해져있을 때 사용할 수 있으며, 괄호()를 이용하여 초기화합니다. 결과는 정해진 크기만큼 동일한 값을 가진 vector가 생성됩니다.

output

10 10 10

 

3. array처럼 초기화 

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    vector<int> vect{ 10, 20, 30 };
 
    for (int x : vect)
        cout << x << " ";
 
    return 0;
}

vector를 array처럼 선언 시 값을 초기화해주는 작업으로 넣을 값이 한 번에 주어졌을 때 사용할 수 있습니다. 중괄호{}를 이용하여 초기화하며 array 초기화시 사용하는 int arr[] = { 10, 20, 30 }; 와 동일한 기능을 한다고 생각하시면 될 것 같습니다.

 

output

10 20 30

 

4.array로부터의 초기화

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    int arr[] = { 10, 20, 30 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    vector<int> vect(arr, arr + n);
 
    for (int x : vect)
        cout << x << " ";
 
    return 0;
}

해당 코드는 array에 있는 값을 옮기기 위해서 사용할 수 있습니다. 

 

output 

10 20 30

 

5. 다른 vector로부터의 초기화

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    vector<int> vect1{ 10, 20, 30 };
 
    vector<int> vect2(vect1.begin(), vect1.end());
 
    for (int x : vect2)
        cout << x << " ";
 
    return 0;
}

4.번과 동일한 원리로 초기화하지만 vector의 경우는 end()를 통해 마지막 값 위치를 알 수 있기 때문에  array에서처럼 array의 원소를 구하지 않아도 됩니다.

 

output

10 20 30

6. 특정 값으로 초기화

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    vector<int> vect1(10);
    int value = 5;
    fill(vect1.begin(), vect1.end(), value);
    for (int x : vect1)
        cout << x << " ";
}

위의 코드는 vect1(10)을 이용하여 10크기의 vector형을 선언합니다. 해당 값은 쓰레기 값을 가지고 있으니, 초기화를 해주어야하며, fill()을 사용하여 처음부터 끝가지 값을 원하는 값으로 채울 수 있습니다.

 

output

5 5 5 5 5 5 5 5 5 5

 

2D vector 초기화

vector도 array와 동일하게 vector의 vector형태로 2D를 지원합니다. 2D vector 초기화 방법을 아래의 포스팅을 참조하여 정리하였습니다.

www.geeksforgeeks.org/2d-vector-in-cpp-with-user-defined-size/

 

2D Vector In C++ With User Defined Size - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

1. array처럼 초기화

#include <iostream>
#include <vector>
using namespace std;
 
int main()
{
     
    vector<vector<int>> vect
    {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
     
    for (int i = 0; i < vect.size(); i++)
    {
        for (int j = 0; j < vect[i].size(); j++)
        {
            cout << vect[i][j] << " ";
        }    
        cout << endl;
    }
 
    return 0;
}

2D array가 1D array의 array인 것 처럼 2D vector도 1D vector의 vector형이기 때문에, 1D 때 vector<int> vect {10, 20, 30};를 이용하여 array처럼 선언한 것과 유사한 방식으로 선언할 수 있습니다. 

 

output 

1 2 3
4 5 6
7 8 9

2D array와 다른 점은 array의 경우 2D array를 구성하고 있는 1D array의 크기는 같아야지만, vector의 경우 사이즈가 다른 vector들을 하나의 vector로 연결할 수 있습니다. 

#include <iostream>
#include <vector>
using namespace std;
int main()
{
     
    vector<vector<int>> vect
    {
        {1, 2}, 
        {4, 5, 6}, 
        {7, 8, 9, 10} 
    };
 
     
    for (int i = 0; i < vect.size(); i++) 
    {
        for (int j = 0; j < vect[i].size(); j++)
        {
            cout << vect[i][j] << " ";
        }    
        cout << endl;
    }
    return 0;
}   

output

1 2 
4 5 6
7 8 9 10

 

2. 특정 크기의 vector를 같은 값으로 초기화

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    int n = 3;
    int m = 4;
 
    vector<vector<int>> vec( n , vector<int> (m, 0)); 
 
    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
        {
            cout << vec[i][j] << " ";
        }
        cout<< endl;
    }
     
    return 0;
}

특정 크기의 1D vector를 특정 값으로 초기화하여 선언하기 위해서 vector<int> vect(n, 10);를 이용했던 것과 유사한 방식으로 2D vector를 생성할 수 있습니다.

output 

0 0 0 0
0 0 0 0
0 0 0 0

 

 

 

 

728x90

댓글