Lesson 58 of 60 – Vector, Map and Set in C++
97%

Vector, Map and Set in C++

C++ STL provides many useful containers for storing and managing collections of data. Three of the most commonly used containers are vector, map, and set.

A vector is useful for storing a sequence of values, a map stores data in key-value pairs, and a set stores unique values.

Note: Choosing the correct container depends on how your program needs to store, access, search, and modify data.

1. What is a Vector?

A vector is an STL container that works like a dynamic array. Unlike a traditional array, its size can grow or shrink during program execution.

#include <vector>

std::vector<int> numbers;

The vector can now store integer values.

2. Creating and Initializing a Vector

A vector can be initialized with values when it is created.

#include <vector>

std::vector<int> numbers = {
    10, 20, 30, 40
};

The vector contains four integer elements.

3. Adding Elements to a Vector

The push_back() function adds an element to the end of a vector.

std::vector<int> numbers;

numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);

The vector becomes:

10 20 30

4. Accessing Vector Elements

Vector elements can be accessed using an index.

std::vector<int> numbers = {
    10, 20, 30
};

std::cout <<
    numbers[0];

std::cout <<
    numbers[1];

The first element has index 0.

5. Vector size() and empty()

The size() function returns the number of elements. The empty() function checks whether the vector contains no elements.

std::vector<int> numbers = {
    10, 20, 30
};

std::cout <<
    numbers.size();

if(!numbers.empty()) {

    std::cout <<
        "Vector is not empty";
}

6. Removing Vector Elements

The pop_back() function removes the last element of a vector.

std::vector<int> numbers = {
    10, 20, 30
};

numbers.pop_back();

The vector now contains:

10 20

7. Traversing a Vector

A range-based for loop provides a simple way to traverse a vector.

std::vector<int> numbers = {
    10, 20, 30
};

for(int number : numbers) {

    std::cout <<
        number << " ";
}

Output:

10 20 30

8. Sorting a Vector

The sort() algorithm can be used to sort vector elements.

#include <algorithm>
#include <vector>

std::vector<int> numbers = {
    40, 10, 30, 20
};

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

The vector becomes:

10 20 30 40

9. Searching in a Vector

The find() algorithm can search for an element.

#include <algorithm>

auto result =
    std::find(
        numbers.begin(),
        numbers.end(),
        20
    );

if(
    result != numbers.end()
) {

    std::cout <<
        "Value found";
}

10. What is a Map?

A map stores data as key-value pairs.

Each key identifies a corresponding value.

#include <map>
#include <string>

std::map<int, std::string> students;

Here, the integer can represent a student ID and the string can represent the student's name.

11. Adding Data to a Map

Values can be inserted into a map using the subscript operator.

std::map<int, std::string> students;

students[101] =
    "Rahul";

students[102] =
    "Priya";

students[103] =
    "Amit";

Each student ID is associated with a name.

12. Accessing a Map Value

A value can be accessed using its key.

std::map<int, std::string> students;

students[101] =
    "Rahul";

std::cout <<
    students[101];

Output:

Rahul

13. Using insert() with Map

The insert() function can also be used to add key-value pairs.

std::map<int, std::string> students;

students.insert({
    101,
    "Rahul"
});

students.insert({
    102,
    "Priya"
});

This is useful when you want to explicitly insert a key-value pair.

14. Traversing a Map

A range-based loop can be used to access map elements.

for(
    const auto& student :
    students
) {

    std::cout <<
        student.first
        << " "
        << student.second
        << std::endl;
}

first represents the key and second represents the value.

15. Finding a Key in a Map

The find() member function can be used to search for a key.

auto result =
    students.find(101);

if(
    result != students.end()
) {

    std::cout <<
        "Student found";
}

If the key does not exist, find() returns end().

16. Updating a Map Value

A value associated with an existing key can be changed.

std::map<int, std::string> students;

students[101] =
    "Rahul";

students[101] =
    "Rahul Kumar";

The value associated with key 101 is now Rahul Kumar.

17. Removing Data from a Map

The erase() function can remove a map element using its key.

students.erase(101);

The entry with key 101 is removed.

18. Map size() and empty()

std::cout <<
    students.size();

if(
    students.empty()
) {

    std::cout <<
        "Map is empty";
}

These functions are useful for checking the current state of a map.

19. What is a Set?

A set is an STL container that stores unique values.

When values are inserted into a standard std::set, they are maintained in sorted order according to the container's comparison rules.

#include <set>

std::set<int> numbers;

20. Inserting Values into a Set

Use the insert() function to add values to a set.

std::set<int> numbers;

numbers.insert(30);
numbers.insert(10);
numbers.insert(20);
numbers.insert(10);

The duplicate 10 is not stored twice.

The set contains:

10 20 30

21. Traversing a Set

A range-based for loop can be used to display set values.

std::set<int> numbers = {
    30, 10, 20
};

for(int number : numbers) {

    std::cout <<
        number << " ";
}

Output:

10 20 30

22. Searching in a Set

The find() function can be used to search for a value in a set.

auto result =
    numbers.find(20);

if(
    result != numbers.end()
) {

    std::cout <<
        "Value found";
}

If the value is not present, find() returns end().

23. Removing Values from a Set

The erase() function can remove a value from a set.

std::set<int> numbers = {
    10, 20, 30
};

numbers.erase(20);

The set now contains:

10 30

24. Comparing Vector, Map and Set

Feature Vector Map Set
Stores Values Key-value pairs Unique values
Duplicate values Allowed Keys are unique Not allowed
Access Index/iterator Key/iterator Iterator/search
Default ordering Insertion sequence Keys ordered Values ordered
Common use Dynamic sequence Lookup by key Unique values

25. Vector of Strings

Vectors can store strings as well as numbers.

#include <string>
#include <vector>

std::vector<std::string> names = {
    "Rahul",
    "Priya",
    "Amit"
};

for(
    const std::string& name :
    names
) {

    std::cout <<
        name << std::endl;
}

This is useful for storing lists of names, courses, cities, or other text values.

26. Practical Student Map

#include <iostream>
#include <map>
#include <string>

int main() {

    std::map<int, std::string> students;

    students[101] = "Rahul";
    students[102] = "Priya";
    students[103] = "Amit";

    int id;

    std::cout <<
        "Enter Student ID: ";

    std::cin >>
        id;

    auto result =
        students.find(id);

    if(
        result != students.end()
    ) {

        std::cout <<
            "Student Name: "
            << result->second;
    }
    else {

        std::cout <<
            "Student not found";
    }

    return 0;
}

This example uses a map to find a student's name using the student ID as the key.

27. Practical Unique Marks Example

#include <iostream>
#include <set>

int main() {

    std::set<int> marks;

    marks.insert(80);
    marks.insert(90);
    marks.insert(80);
    marks.insert(75);
    marks.insert(90);

    std::cout <<
        "Unique marks:\n";

    for(int mark : marks) {

        std::cout <<
            mark << " ";
    }

    return 0;
}

The set stores each mark only once.

28. Common Mistakes

  • Accessing a vector using an invalid index.
  • Assuming a map allows duplicate keys.
  • Expecting a set to store duplicate values.
  • Using a vector when direct key-based lookup is required.
  • Using a map when only unique values are needed.
  • Forgetting that a standard map and set maintain ordered elements according to their comparison rules.
  • Dereferencing an iterator equal to end().
  • Modifying containers while iterating without understanding iterator invalidation rules.

29. Best Practices

  • Use vector for general-purpose dynamic sequences.
  • Use map when data is naturally represented by unique keys and values.
  • Use set when only unique values are required.
  • Use const references when reading container elements without modifying them.
  • Use find() to test whether a key or value exists.
  • Use range-based for loops for simple traversal.
  • Choose the container according to the operations your program performs most often.

30. Vector, Map and Set – Final Summary

Container Main Purpose Example
vector Store a dynamic sequence of values. Student marks
map Store key-value pairs. Student ID → Name
set Store unique values. Unique marks
#include <iostream>
#include <map>
#include <set>
#include <vector>

int main() {

    std::vector<int> marks = {
        80, 90, 75
    };

    std::map<int, std::string> students;

    students[101] = "Rahul";
    students[102] = "Priya";

    std::set<int> uniqueMarks;

    uniqueMarks.insert(80);
    uniqueMarks.insert(90);
    uniqueMarks.insert(80);

    std::cout <<
        "Vector size: "
        << marks.size()
        << std::endl;

    std::cout <<
        "Student 101: "
        << students[101]
        << std::endl;

    std::cout <<
        "Unique marks: ";

    for(int mark : uniqueMarks) {

        std::cout <<
            mark << " ";
    }

    return 0;
}

The three containers solve different problems. A vector stores a dynamic sequence, a map connects keys with values, and a set keeps unique values.

📌 Key Points

  • vector is a dynamic sequence container.
  • push_back() adds an element to the end of a vector.
  • map stores key-value pairs.
  • Map keys are unique.
  • find() can be used to search a map key.
  • set stores unique values.
  • Duplicate values are not stored multiple times in a standard set.
  • insert() adds elements to maps and sets.
  • erase() removes elements.
  • Choose the container according to the data and operations required.

🧠 Quick Quiz

Question: Which STL container stores data as key-value pairs?