C++ - STL (Standard Template Library) - Using the vector container

The vector container is the most classic STL container.

In the snippet below, I can iterate through the vector, so I use an iterator to erase an element of the vector.
In our case, I removed the number 2 from the container and I added 80 to this place.

Let's see this example of the vector container.

Code

#include <vector>
#include <iostream>

int main()
{
  std::vector<int> myVector;
  std::vector<int>::iterator myIterator;
  int i;

  i = 0;
  while (i < 10)
    {
      myVector.push_back(i++);
    }
  for(myIterator = myVector.begin(); myIterator != myVector.end(); ++myIterator)
    {
      if (*myIterator == 2)
        {
          myVector.erase(myIterator);
          myVector.insert(myIterator,  80);
        }
    }
  for(myIterator = myVector.begin(); myIterator != myVector.end(); ++myIterator)
    {
      std::cout << "*myIterator = " << *myIterator << std::endl;
    }
  return 0;
}

Result:

*myIterator = 0
*myIterator = 1
*myIterator = 80
*myIterator = 3
*myIterator = 4
*myIterator = 5
*myIterator = 6
*myIterator = 7
*myIterator = 8
*myIterator = 9
A really helpful container! angel

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Refresh Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, submit the form and a new image will be generated. Not case sensitive.  Switch to audio verification.