How to add elements to a string array

To add elements to a string array, you can use the push() method of the array or directly assign values through indexing.

Utilize the push() method:

#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;
}

Assign values directly through indexing.

#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;
}

You can add elements to a string array using any method.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds