C++ vector delete item

Introduction

One learns to appreciate the ease of use of range-based for loops instead of this old-school iterator usage in a for-loop.

Now that we know about iterators, we can use them to erase elements from a vector.

Let us say we want to erase the third element.

We position the iterator to a third element and use the.erase(iterator_name) member function:

#include <iostream> 
#include <vector> 

int main() //from  w  w w. j  a va2s .  c  om
{ 
    std::vector<int> v = { 1, 2, 3, 4, 5 }; 
    auto it = v.begin() + 3; 
    v.erase(it); 

    for (auto el : v) 
    { 
        std::cout << el << '\n'; 
    } 
} 

We also mentioned another group of containers called associative containers.

These containers are implemented as binary trees.

They allow for quick search times, and the data in these containers is sorted.

These associative containers are std::set and std::map.

Set holds unique values.

Map holds pairs of key-value elements.

Maps hold unique keys.

Please note that there is also another group of associative containers that allow for duplicate values.

They are std::multi_set and std::multi_map.




PreviousNext

Related