for vector c++
To declare a vector in C++, follow these steps:
- Include the necessary header file for vectors:
#include <vector>
- Declare a vector of a specific data type:
std::vector<int> myVector;
- Initialize the vector with a specific size and default value:
std::vector<int> myVector(5, 0);
- Add elements to the vector using
push_back
:
myVector.push_back(10);
- Access elements using the index operator:
int value = myVector[0];
- Iterate through the vector using iterators:
for (auto it = myVector.begin(); it != myVector.end(); ++it) {
// Access *it
}
- Get the size of the vector using the
size
method:
int size = myVector.size();
- Remove elements from the vector using
pop_back
:
myVector.pop_back();
- Clear all elements from the vector:
myVector.clear();