C++ / Guided lesson

Explore C++ Vectors and STL Algorithms

Strengthen your C++ programming skills through arrays, pointers, references, vectors, object-oriented programming, and Standard Template Library algorithms.

Browse all C++ topics

Worked example

C++ is a compiled, general-purpose programming language. The Standard Template Library (STL) provides containers and algorithms. A vector is a dynamic array, and std::sort() arranges elements in a specified order.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> numbers = {50, 20, 80, 10, 40};

    sort(numbers.begin(), numbers.end());

    cout << "Sorted Numbers: ";

    for (int number : numbers) {
        cout << number << " ";
    }

    cout << endl;

    return 0;
}

Expected output

Sorted Numbers: 10 20 40 50 80

Check your understanding

What is the difference between an array and a vector in C++?

Show answer

A built-in C++ array has a fixed size determined at creation. A std::vector is a dynamic container that can grow or shrink during execution. Vectors provide useful methods such as push_back(), size(), and pop_back().

Try it yourself

Modify the program to sort the numbers in descending order using the STL sort() function.

Show solution
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;

int main() {
    vector<int> numbers = {50, 20, 80, 10, 40};

    sort(numbers.begin(), numbers.end(), greater<int>());

    for (int number : numbers) {
        cout << number << " ";
    }

    return 0;
}

// Output: 80 50 40 20 10

C++ / Full curriculum

All C++ Topics

Choose a topic to study the explanation, code, output, questions, and practice exercises.

Lesson 1 / 59

C++ · Lesson 1 of 59

Introduction and Hello World

1. Understand the idea

C++ lets you write programs that run fast and give you control over how data is stored. You start by writing a small program that shows a message.

Think of a real-life example

Just like writing a recipe, you give the computer steps to follow in order.

2. Read the example

Read the code slowly. Before checking the output, try to guess what will happen.

#include <iostream>
using namespace std;
int main() {
    cout << "Hello, AskBun!" << "\n";
    return 0;
}

What happens in this code?

main is where the program begins. cout sends text to the screen, and return 0 says the program finished normally.

Expected output

Hello, AskBun!

3. A mistake to avoid

You usually compile C++ before running it. Match braces carefully and end ordinary statements with ;.

New words explained simply
object
A real item made from a class.

4. Check your understanding

What does cout do?

Writes output to the standard output stream.

5. Try it yourself

Try the task on your own first. It is okay to get it wrong—that is part of learning. Then open the solution to compare.

Print your favorite language.

Back to all subjects