Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any analogue for Java Collections.singleton() in C++?

In Java, I can construct a collection of single element by calling:

Collection<String> c = Collections.singleton("foo");

Is there a similar one-liner for std::vector or std::set construction in C++ (in Boost or whatever)?

like image 751
weekens Avatar asked Dec 11 '25 05:12

weekens


1 Answers

No, but there is also no need for it. In C++11 you can leverage the compiler's magic support for std::initializer_list<T> (and the new vector constructor that accepts one) by simply writing

vector<string> vec { "foo" };

The same goes for std::set.

like image 94
Jon Avatar answered Dec 13 '25 19:12

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!