Examples C++

Fill, Insert, Sort, and Remove Entries in an STL vector

In this C++ example, we demonstrate how to perform basic operations with an STL vector. We start by pushing three ints into the back of the vector. Then we insert the value 10 into the second place. Next, we sort the vector. Finally, we erase the last three entries in the vector. After each of these operations, we output the vector to show what is in it.

Code:

#include <iostream>
#include <vector>
#include <algorithm>

void PrintVector(std::vector<int>& qrVector) {
    std::vector<int>::iterator qIter;
    for (qIter = qrVector.begin(); qIter != qrVector.end(); ++qIter) {
        std::cout << *qIter << "  ";
    }
    std::cout << std::endl;
}

int main()
{
    using namespace std;

    vector<int> qVector;
    // Add three entries at the back of the vector
    qVector.push_back(45);
    qVector.push_back(34);
    qVector.push_back(2);
    PrintVector(qVector);

    // Insert an entry into a vector after the first
    vector<int>::iterator qIter = qVector.begin();
    ++qIter;
    qVector.insert(qIter, 10);
    PrintVector(qVector);

    // Sort the entries in the vector and output them
    sort(qVector.begin(), qVector.end());
    PrintVector(qVector);

    // Remove the second up through the last entries
    qIter = qVector.begin();
    ++qIter;
    qVector.erase(qIter, qVector.end());
    PrintVector(qVector);

    return 0;
}

Output:

Output
 

© 2007–2024 XoaX.net LLC. All rights reserved.