Open In App

How to Initialize Vector of Char Arrays in C++?

Last Updated : 29 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ Program to illustrate how to initialize a vector of
// char arrays
#include <iostream>
#include <vector>
using namespace std;
  
// Driver Code
int main()
{
    // Creating a vector of char arrays
    vector<const char*> myVector
        = { "apple", "banana", "cherry" };
  
    // Displaying the vector elements
    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)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads