본문 바로가기
개인 개발 공부/C ++

1-8. 배열과 2차원 배열

by minjoothi 2024. 11. 11.

배열 (Array)

c++ 배열은 좀 다름

같은 데이터 타입의 값들을 연속된 메모리 공간에 저장하는 자료 구조입니다. 배열을 사용하면 여러 개의 변수를 따로 선언하지 않고, 하나의 이름으로 여러 데이터를 관리할 수 있습니다.

// array.cpp
#include <iostream>

int main()
{
    using namespace std;
    int score[3] = {100, 90, 20}; // 3개짜리 score를 담을 int형 배열
    int midScore[3] = {0,}; //0,는 다 0으로 채울거임이라는 뜻
    int finalScore[] = {10, 20, 90};  //몇개가 듣어갈지 모르겠을땐 비워놓기

    cout << score[0] << endl; // score 0번째 배열 출력,100
    cout << midScore[1] << endl; // midscore 1번째 배열 출력,0
    cout << finalScore[2] << endl; //finalscore 2번째 배열 출력, 90
    
    // 
    

    cout << "&score: " << &score << endl;  //score주소내놔
    cout << "&score[0]: " << &score[0] << endl; //score의 0번째 주소 내놔
    cout << "&score[1]: " << &score[1] << endl; //score 1번째 주소 내놔 = 0 번째 주소랑 같음
    cout << "(score+1): " << (score+1) << endl; //score에서 1번째 더한 주소 내놔
    cout << "*(score + 1): " << *(score + 1) << endl; //주소에 1을 더하고 값을 알려줘

    return 0;
}

문자열 (String) 

class는 그냥 int 같은애임

쉽게 문자열을 출력해줄 수 있음

// string.cpp
#include <iostream>

int main()
{
    using namespace std;
    string sparta = "Sparta";
    string coding = "Coding";
    string club = "Club";
    string result = sparta + coding + club; 

    cout << result << endl;
    cout << result.size() << endl; // 문자열의 길이
    cout << result.substr(sparta.size(), result.size()) << endl; //여기서부터 저기 사이즈까지
    cout << result.find(club) << endl;
    return 0;
}

2차원 배열 예제

// 2darray.cpp
#include <iostream>

int main()
{
    using namespace std;

    const int row = 5; //const 는 앞으로 바뀌지 않을거다란 뜻, c++에서 중요
    const int col = 5;
    int counter = 0;
    int map[row][col] = {0};

    for (int i = 0; i < row; i++)  // 0,1,2,3,4 행
    {
        for (int j = 0; j < col; j++) // 0,1,2,3,4, 열
        {
            map[i][j] = counter++; //map을 만들어준당
            cout << map[i][j] << "\t";
        }
        cout << endl;
    }

    return 0;
}

  • for (int i = 0; i < row; i++): 이 루프는 행(row)을 제어합니다.
  • for (int j = 0; j < col; j++): 이 루프는 각 행의 열(column)을 제어합니다.
  • map[i][j] = counter++;: 배열 map[i][j]에 counter 값을 넣고, counter를 1 증가시킵니다.
  • cout << map[i][j] << "\t";: map[i][j] 값을 출력하고 탭(\t)으로 간격을 줍니다.
  • cout << endl;: 한 행이 끝날 때 줄바꿈을 합니다.

'개인 개발 공부 > C ++' 카테고리의 다른 글

1-7. 포인터와 참조  (0) 2024.11.11
1-6 함수  (1) 2024.11.10
1-5 반복문과 다중반복문  (0) 2024.11.09
조건문  (0) 2024.11.09
연산자  (0) 2024.11.09