To create a vector of strings in C++, you can use the std::vector class and the push_back method to add strings to the vector.
In this example,
header to use the std::vector
class.str_vector
of type std::vector
.push_back
method to add strings one by one to the vector.#include <vector>
#include <iostream>
#include <string>
int main() {
std::vector<std::string> str_vector;
str_vector.push_back("apple");
str_vector.push_back("banana");
str_vector.push_back("cherry");
str_vector.push_back("date");
str_vector.push_back("grape");
for (const std::string& str : str_vector) {
std::cout << str << " ";
}
std::cout << std::endl;
return 0;
}
apple banana cherry date grape
In this example,
header to use the std::vector
class.str_vector
and initialize it with a list of strings inside curly braces {}
.#include <vector>
#include <iostream>
#include <string>
int main() {
std::vector<std::string> str_vector = {"apple", "banana", "cherry", "date", "grape"};
for (const std::string& str : str_vector) {
std::cout << str << " ";
}
std::cout << std::endl;
return 0;
}
apple banana cherry date grape
In this tutorial, we learned How to create a Vector of Strings in C++ language with well detailed examples.