C++ 문자열의 배열 만드는 방법

배열의 포인터 사용

#include <iostream>
using namespace std; 

int main() {
  const char* color[3] = {"red", "blue", "green"};

  for (auto col : color){
      cout << col << endl;
  }
    
  return 0;
}

Drawbacks:

  • Number of strings are fixed
  • Strings are constants and contents cannot be changed.

2차원 배열 사용

#include <iostream>
using namespace std;

int main()
{
    // Char “Name” [“Number of Strings”][“MaxSize of String”]
    char color[3][10] = {"red", "blue", "green"};

    for (auto col : color)
    {
        cout << col << endl;
    }

    return 0;
}

Drawbacks:

  • Both the number of Strings and Size of String are fixed.
  • A 2D array is allocated, whose second dimension is equal to maximum sized string which causes wastage of space.

string 사용

#include <iostream>

using namespace std;

int main()
{
    vector<string, 3> color = {"red", "blue", "green"};

    for (auto col : color)
    {
        cout << col << endl;
    }

    return 0;
}

Drawback: The array is of fixed size.

vector 사용

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<string> color = {"red", "blue", "green"};

    for (auto col : color)
    {
        cout << col << endl;
    }

    return 0;
}