lornova
lornova

Reputation: 6933

Iterate an std::vector by capacity

When I fill an std::vector knowing in advance the final size, I usually reserve its capacity in advance to avoid reallocation of its content (which on C++03 involves calling copy constructors for each object already stored in the vector).

This is a trivial example:

std::vector<std::string> v;
v.reserve(10);    

for( std::vector<std::string>::size_type i = 0, capacity = v.capacity();
     i < capacity;
     ++i )
{
    v.push_back(std::to_string(i));
}

There's a better way (less C-style) to loop around the std::vector capacity?

I'm looking for both C++03 and C++11 answers.

Edit: I rewrote the sample because all the answers and comments were going off topic, concerning only filling the std::vector with an array, which is not the point of the question.

Upvotes: 0

Views: 413

Answers (2)

Cory Kramer
Cory Kramer

Reputation: 117866

You don't really need a loop at all. There is an overload of std::vector constructor that takes two iterators. So just use std::begin and std::next to get the start and end of the passed-in array and make a vector from that.

template<typename T>
std::vector<T> fill(const T* t, size_t size)
{
    return {std::begin(t), std::next(std::begin(t), size)};
}

Similarly you could use pointer arithmetic, which is what the above method essentially does under the hood:

template<typename T>
std::vector<T> fill(const T* t, size_t size)
{
    return {t, t + size};
}

Upvotes: 6

Richard Hodges
Richard Hodges

Reputation: 69882

In c++11 or better, if you fill a vector knowing its size std::initializer_list will be your best bet.

You probably want to avoid initialising through a pointer to an array of const objects because that almost guarantees a copy. I appreciate that this is necessary in c++03, which should be one of your main motivations to move to a newer compiler if possible.

so:

std::vector<Thing> mythings { Thing(1), Thing(2), Thing(3) };

Is about as fast as you can get it. (not that there is no need for a fill function).

If you compile this on a reasonably modern compiler with optimisations on, you'll find that the Things will actually be created in-place within the vector. There is no faster way.

Upvotes: 0

Related Questions