Question

Suppose I want to construct a C++ STL vector from an array (knowing its length), i.e. I have:

size_t length = /* ... */
int *a = new int[length];

I can construct the vector this way:

std::vector<int> v(a, a + length);

but not this way:

std::vector<int> v(a, length);

Why doesn't the vector class have the latter kind of constructor?

Was it helpful?

Solution

Because that constructor is the typical begin-end constructor:

template< class InputIt >
vector( InputIt first, InputIt last, 
        const Allocator& alloc = Allocator() );

which copies the content from first to last (not included) and does not take ownership of the allocated dynamic array.

Most of the STL's algorithms uses the [begin, end) range, and for consistency, also does this constructor.

OTHER TIPS

C++ standard library almost always prefer a begin/end pair to a start/length pair. That consistency is worth something.

Its common for people to want "just one more thing" but people are very bad at agreeing on whats the most important one more thing to add. So when you have an interface that does the job, fattening it to add a ctr that doesn't really help many people very often, and would reduce consistency is a hard sell.

Because there is no need for such code bloat within the standard library when, as you've already pointed out, the functionality exists perfectly well with the existing constructor.

Standard containers typically function on ranges.

Taking a pointer and a length is more of a C-string idiom; note that std::string does have such a constructor, accordingly.

Why doesn't the vector class have the latter kind of constructor?

Because it would be superfluous. You can already construct containers on iterator sequences (a consistent design decision throughout stl), so the extra constructors would not add anything new; The only reason for having that kind of constructor would be if switching from iterator pairs to iterator-count pair were non-trivial in client code.

The way of describing sequences was heavily used in C; that doesn't mean it makes for good C++.

Side note: please please don't use malloc in C++ (not in production code, not in "write-once" code, not for simple examples on SO and/or elsewhere); it gives others a bad code example and encourages a habit for bad code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top