
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Array of Strings
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
#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
#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
Advertisements