How to use the vector class In C++
A vector is a dynamic array that doubles its size whenever a new character is added that exceeds its limit. The STL container vector can be used to dynamically allocate an array that can vary in size.
This is only usable in C++, as C does not have classes. Note that the initializer-list syntax here requires a compiler that supports the 2011 C++ standard, and though it is quite likely your compiler does, it is something to be aware of.
Example:
C++
// C++ program to demonstrate // array of strings using // vector class #include <iostream> #include <string> #include <vector> // Driver code int main() { // Declaring Vector of String type // Values can be added here using // initializer-list // syntax std::vector<std::string> colour{ "Blue" , "Red" , "Orange" }; // Strings can be added at any time // with push_back colour.push_back( "Yellow" ); // Print Strings stored in Vector for ( int i = 0; i < colour.size(); i++) std::cout << colour[i] << "\n" ; } |
Blue Red Orange Yellow
Explanation:
- Vectors are dynamic arrays and allow you to add and remove items at any time.
- Any type or class may be used in vectors, but a given vector can only hold one type.
Array of Strings in C++ – 5 Different Ways to Create
In C++, a string is usually just an array of (or a reference/points to) characters that ends with the NULL character ‘\0‘. A string is a 1-dimensional array of characters and an array of strings is a 2-dimensional array of characters where each row contains some string.
Below are the 5 different ways to create an Array of Strings in C++:
- Using Pointers
- Using 2-D Array
- Using the String Class
- Using the Vector Class
- Using the Array Class