Jay Bazuzi
Jay Bazuzi

Reputation: 46536

How to promote an empty vector to a vector of one default element?

Today I have this:

std::vector<Foo> foos = GetFoos();
if (foos.empty())
{
    foos.push_back(Foo());
}

I'd love to write something like:

std::vector<Foo> foos = GetFoos() || {Foo()};

Is there something handy like that, perhaps in Boost?

Upvotes: 0

Views: 70

Answers (2)

R Sahu
R Sahu

Reputation: 206667

I am not sure whether there are enough tricks in the language to support the syntax

std::vector<Foo> foos = GetFoos() || {Foo()};

It will be better to write a function that clearly expresses your intent and use it.

void ensureAtLeastOneElement(std::vector<Foo>& v)
{
   if (v.empty())
   {
      v.push_back(Foo());
   }
}

and use it as:

std::vector<Foo> foos = GetFoos();
ensureAtLeastOneElement(foos);

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385274

Well, since resizing a vector to its existing size is a no-op, and since resizing it to be bigger than it already is will default-construct the new elements, you could do this:

std::vector<Foo> foos = GetFoos();
foos.resize(std::max(1, foos.size()));

However, I actually prefer your first example; it's much clearer and signifies intent.

But is there a one-liner? No, thank goodness.

Upvotes: 1

Related Questions