How to Initialize Vector of Char Arrays in C++?
Last Updated :
29 Feb, 2024
In C++, a vector is a dynamic array that can grow and shrink in size. A char array is a sequence of characters, typically used to represent strings. In this article, we will learn how to initialize a vector of char arrays in C++.
Example:
myVector: {“apple”, “banana”, “cherry”}
Initializing a Vector of Char Arrays in C++
We cannot directly store the char array into the vector, but we can store them as pointers. To initialize a vector of char arrays in C++, we can use the list initialization where each element is a string literal. The pointer to this string literal is then stored inside the vector of char arrays.
Note: It is strongly recommended to avoid using array or pointer to arrays as the data type of the vector.
C++ Program to Initialize a Vector of Char Arrays
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< const char *> myVector
= { "apple" , "banana" , "cherry" };
for ( int i = 0; i < myVector.size(); ++i) {
cout << myVector[i] << endl;
}
return 0;
}
|
Output
apple
banana
cherry
Time Complexity: O(N), where N is the number of char arrays.
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...