string配列に要素を追加する方法は何ですか?

stringの配列に要素を追加するには、push()メソッドを使用するか、インデックスを直接指定して値を代入する方法があります。

push()メソッドを使用します。

#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> myArray;

    myArray.push_back("Hello");
    myArray.push_back("World");

    for (std::string element : myArray) {
        std::cout << element << " ";
    }

    return 0;
}

インデックスを使用して直接割り当てる:

#include <iostream>
#include <string>

int main() {
    std::string myArray[2];

    myArray[0] = "Hello";
    myArray[1] = "World";

    for (std::string element : myArray) {
        std::cout << element << " ";
    }

    return 0;
}

どの方法を使用しても、string配列に要素を追加することができます。

bannerAds