Open In App

How to Access Elements in a Vector of Char Arrays?

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 access elements in a vector of char arrays in C++.

Example:

Input: 
myVector = {“apple”, “banana”, “cherry”}

Output: 
myVector[1] = banana

Access Vector of Char Arrays Elements in C++

We store the array of characters inside the vector as pointers. To access elements in a std::vector of char arrays in C++, we can use the operator[] that takes the index as an argument and returns the element at that index in the vector.

C++ Program to Access Elements in a Vector of Char Arrays

C++




// C++ Program to illustrate how to access elements in 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" };
  
    cout << "Accessing the elements in the vector using "
            "operator[]"
         << endl;
  
    cout << "myVector[2]: " << myVector[2] << endl;
  
    return 0;
}


Output

Accessing the elements in the vector using operator[]
myVector[2]: cherry

Time Complexity: O(1)
Space Complexity: O(1)


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

Similar Reads