C++ Array of Strings

C++Server Side ProgrammingProgramming

In this section we will see how to define an array of strings in C++. As we know that in C, there was no strings. We have to create strings using character array. So to make some array of strings, we have to make a 2-dimentional array of characters. Each rows are holding different strings in that matrix.

In C++ there is a class called string. Using this class object we can store string type data, and use them very efficiently. We can create array of objects so we can easily create array of strings.

After that we will also see how to make string type vector object and use them as an array.

Example

 Live Demo

#include<iostream>
using namespace std;
int main() {
   string animals[4] = {"Elephant", "Lion", "Deer", "Tiger"}; //The
   string type array
   for (int i = 0; i < 4; i++)
      cout << animals[i] << endl;
}

Output

Elephant
Lion
Deer
Tiger

Now let us see how to create string array using vectors. The vector is available in C++ standard library. It uses dynamically allocated array.

Example

 Live Demo

#include<iostream>
#include<vector>
using namespace std;
int main() {
   vector<string> animal_vec;
   animal_vec.push_back("Elephant");
   animal_vec.push_back("Lion");
   animal_vec.push_back("Deer");
   animal_vec.push_back("Tiger");
   for(int i = 0; i<animal_vec.size(); i++) {
      cout << animal_vec[i] << endl;
   }
}

Output

Elephant
Lion
Deer
Tiger
raja
Published on 03-Apr-2019 07:21:58
Advertisements