Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Half-open iterator range constructor

The iterator pair first and last describes [first, last): the beginning is included and the end is excluded. The std::vector range constructor constructs elements from that range; equal boundaries describe an empty range.

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

Syntax

std::vector<T> destination(first, last); // elements in [first, last)

Half-open iterator range constructor means a constructor taking an iterator pair, such as std::vector<T> destination(first, last). The notation [first, last) includes the element pointed to by first but excludes the element pointed to by last. When first == last, the range is empty.

last must be reachable from first through finitely many increments. The iterators must remain valid while being read. Do not dereference a past-the-end iterator; passing an invalid range to a library function causes undefined behavior.

In general, a range can end with a sentinel of a different type. However, this std::vector constructor takes two arguments of the same InputIterator type meeting input iterator requirements. It constructs elements rather than creating a view of the source.

In the example, source + 1 points to 20, while the excluded boundary source + 3 points to 40: selected therefore contains 20 and 30. The pair source, source constructs an empty vector. These operations are available in C++23; the cited document is an evolving standard draft, not a frozen C++23 publication.

Examples

#include <iostream>
#include <vector>

int main() {
    const int source[] = {10, 20, 30, 40};
    std::vector<int> selected(source + 1, source + 3);
    std::vector<int> empty(source, source);

    std::cout << selected.size() << ':';
    for (int value : selected) {
        std::cout << ' ' << value;
    }
    std::cout << '\n' << empty.size() << '\n';
}

Result

2: 20 30
0

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