0

I am looking for vanilla C++98 solution (no boost, or qt, etc.)

Is there a way to do something like this :

// valid in c++ 11
std::vector<Foo> vFoo {Foo1, Foo2, Foo3, Foo4} ;

or something like this

// Well it is C# but you got the point.
List<Foo> lFoo = new List<Foo>() { Foo1, Foo2, Foo3, Foo4 };

For now, I use this one :

std::vector<Foo> vFoo;
vFoo.push_back(Foo1);
vFoo.push_back(Foo2);
vFoo.push_back(Foo3);
vFoo.push_back(Foo4);

But I find it ugly. Any idea to improve it ? Is there a special way to achieve it ?

Thank you.

aloisdg
  • 22,270
  • 6
  • 85
  • 105

3 Answers3

1

Short answer: No. That's why language support for such constructions was added in C++11. Your existing push_back solution is adequate if you cannot use C++11.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • I used my own answer finally. By the way, I love this [one](http://stackoverflow.com/a/2236227/1248177). – aloisdg Apr 05 '14 at 13:10
  • @aloisdg: I don't know, I would call putting variable functions into C++ an outright disservice, to yourself, to future readers, and to humanity. Just say no. (And yes, initializing from an existing collection has always been easy. But that's doing something different.) – Kerrek SB Apr 05 '14 at 13:11
0

I build my own solution using va_arg.

#include <cstdarg>
#include <iostream>
#include <vector>

template <typename T>
std::vector<T> initVector (int len, ...)
{
  std::vector<T> v;
  va_list vl;
  va_start(vl, len);
  v.push_back(va_arg(vl, T));
  for (int i = 1; i < len; ++i)
    v.push_back(va_arg(vl, T));
  va_end(vl);
  return v;
}

int main ()
{
  std::vector<int> v = initVector<int> (7,702,422,631,834,892,104,772);
  for(std::vector<int>::const_iterator it = v.begin() ; it != v.end(); ++it)
    std::cout << *it << std::endl;
  return 0;
}

If you want more answers, follow the link of Doc Brown.

Community
  • 1
  • 1
aloisdg
  • 22,270
  • 6
  • 85
  • 105
  • 1
    Please bear in mind that this works only for POD types (the fundamental data types, plus classes without user-defined constructors, virtual members, references etc.). C++03 standard reference: 5.2.2/7. – j_random_hacker Apr 05 '14 at 13:31
  • Thanks for the comment. [I learn something new today](http://stackoverflow.com/questions/146452/what-are-pod-types-in-c). – aloisdg Apr 05 '14 at 13:34
  • You're welcome. C++ is full of dark corners I'm afraid ;) – j_random_hacker Apr 05 '14 at 20:18
0

You can initialize a vector from an array:

Foo[] initFoo = { Foo1, Foo2, Foo3, Foo4 };
std::vector<Foo> vFoo(initFoo, initFoo + 4);
Ferruccio
  • 98,941
  • 38
  • 226
  • 299