복습이 필요한 알고 팁
동적 2차원 배열 + 특정 수로 초기화 하기
헐랭미
2020. 9. 5. 03:41
만약 x,y를 입력 받아서 x행 y열의 2차원 벡터와 각 공간에 10이라는 수로 초기화 하고 싶다.
방법 1. 무식하게.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int arr[100][100];
int x,y;
cin >> x >> y;
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
arr[i][j] = 10;
cout << arr[i][j] << ' ';
}
cout << '\n';
}
}
|
cs |
방법 2. fill을 사용 (x-1,y-1 이니 x-1,y 까지 범위 입력 한다.)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int arr[100][100];
int x;
int y;
cin >> x >> y;
fill(&arr[0][0], &arr[x-1][y], 10);
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
cout << arr[i][j] << ' ';
cout << '\n';
}
}
|
cs |
근데 둘다 arr[100][100] 처럼 이렇게 초기 배열이 있어야 한다.
하지만 vector<int>를 사용하여 이런거 없이도 만들 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int x = 5;
int y = 4;
vector<vector<int>> arr(x, vector<int>(y, 10));
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
cout << arr[i][j] << ' ';
cout << '\n';
}
}
|
cs |