Variables

Vectors in C++

C++ has a vector class within the std namespace. A vector is similar to an array, in a sense where a series of elements are stored with the same variable name. Unlike arrays, vectors are dynamically sized, which is a major advantage.


Syntax
vector<dataType> vectorName;

//if you want to provide a size
vector<dataType> vectorName(size);

//adding an item to a vector
vectorName.push_back(value);

//accessing an index of a vector
vectorName[index];

//changing a value at a certain index
vectorName[index] = value;

Notes

Since a vector is within the std namespace, you either have to 'use' the namespace or type out std::vector.


Example
using namespace std;

//declaration
vector<int> powersOfTwo;

//adding members
powersOfTwo.push_back(1);
powersOfTwo.push_back(0);
powersOfTwo.push_back(4);
powersOfTwo.push_back(8);

//accessing
cout << "2 ^ 3 = " << powersOfTwo[3];

//accessing and changing
powersOfTwo[1] = 2;

See Also
Related

Array

Documentation

vector - C++ Reference

Add to Slack

< Type Definition   |   Smart Pointers >

© 2019 SyntaxDB. All Rights Reserved.