What is the Vector in C++


The Standard Library defines a container object called a "vector". The "vector" is a class that contains items of the type specified in the angle brackets <> .The vector is initialized in a special way that is new to C++11, called list initialization. This syntax allows you to specify the initial values of the vector in a list between curly braces.

We use #include <vector> to recognize the vector class. The vector class has a member function called "size" calling through the . operator, it will return the number of items in the vector. Each item is accessed using the "at" function passing the item's index.

There are two different ways to print out the items from the vector.
#include <iostream>
#include <string>
#include <vector> //calling the vector class to use.
using namespace std;
int main()
{
vector<string> myarray = {"John", "Timmy", "Harry"};
//the first way
for (int i = 0; i < myarray.size(); ++i)
{
cout << myarray.at(i) << endl;
}
cout << endl << endl;
//the second way
for (string name : myarray)
{
cout << name << endl;
}
system("pause");
return 0;
}
view raw gistfile1.txt hosted with ❤ by GitHub

What is the Vector in C++

No comments:

Post a Comment