Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Collections and containers

A collection is a general term for a group of elements. The C++ standard library provides containers with different storage and access rules: sequences, associative containers, and adaptors.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

std::vector<T> values;
values.push_back(value);
for (const auto& element : values) { /* use element */ }

collections names a concept, not a C++ keyword or type. Standard library containers store elements of a specified type; for example, std::vector<int> stores int values.

Sequence containers such as std::vector and std::array organize elements into a sequence; std::array has a fixed number of elements. std::map associates keys with values, while std::set stores keys; both order keys according to a comparator and disallow equivalent keys. The multi variants allow such keys. The unordered containers use hashing and do not guarantee sorted iteration order. Adaptors such as std::stack and std::queue expose a restricted set of operations over an underlying container.

In the example, values.push_back(5) appends an element, and the loop sums every value, including duplicates. std::vector<int> stores its elements contiguously. Appending has amortized constant cost; insertion in the middle has linear cost. Reallocation invalidates all pointers, references, and iterators to elements, so do not retain them without checking the invalidation rules.

This entry targets C++23. The supplied site presents an evolving working draft, not a frozen C++23 text; this entry does not assume later additions are available. A repository compiler flag does not establish production runtime support.

Examples

#include <iostream>
#include <vector>

int main() {
    std::vector<int> values{3, 1, 3};
    values.push_back(5);

    int sum = 0;
    for (int value : values) {
        sum += value;
    }

    std::cout << "size=" << values.size() << '\n';
    std::cout << "sum=" << sum << '\n';
}

Result

size=4
sum=12

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources