accessing elements in a vector c++ code example
Example 1: remove element by index from vector c++
vec.erase(vec.begin() + 1);
vec.erase(vec.begin() + 1, vec.begin() + 3);
Example 2: c++ remove element from vector
vector.erase(position)
vector.erase(left,right)
Example 3: vector by index c++
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector (10);
std::vector<int>::size_type sz = myvector.size();
for (unsigned i=0; i<sz; i++) myvector[i]=i;
for (unsigned i=0; i<sz/2; i++)
{
int temp;
temp = myvector[sz-1-i];
myvector[sz-1-i]=myvector[i];
myvector[i]=temp;
}
std::cout << "myvector contains:";
for (unsigned i=0; i<sz; i++)
std::cout << ' ' << myvector[i];
std::cout << '\n';
return 0;
}
Example 4: cpp access vector by index
std::vector<int> vecOfNums{ 1, 4, 5, 22, 33, 2, 11, 89, 49 };
int & element = vecOfNums[3];