만약 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 |
'복습이 필요한 알고 팁' 카테고리의 다른 글
java로 알고리즘 만들기 (0) | 2020.09.06 |
---|---|
set을 더 잘써보자. (multiset 과 기타 잡팁들...) (0) | 2020.09.05 |
vector<int> 에서 .erase()쓰기 (0) | 2020.08.30 |
nCr 좀 더 간단하게 (r 이 작으면서 고정적인 값일때) (0) | 2020.08.29 |
정렬 STL을 잘 써보자 (0) | 2020.06.26 |