Home >Backend Development >C++ >How Can I Elegantly Initialize a std::vector with Hardcoded Elements in C ?
Elegant Initialization of std::vector with Hardcoded Elements
While it's straightforward to initialize an array in C , e.g., int a[] = {10, 20, 30}, initializing a std::vector in a similar fashion may seem cumbersome. Here are two elegant ways to achieve the same result:
C 11 Initializer List
In C 11 and later, you can use initializer lists to initialize a std::vector directly:
std::vector<int> v = {1, 2, 3, 4};
This syntax is supported by GCC from version 4.4. However, VC 2010 does not yet support this feature.
Boost.Assign Library
Alternatively, the Boost.Assign library provides a convenient way to initialize a std::vector:
#include <boost/assign/list_of.hpp> ... std::vector<int> v = boost::assign::list_of(1)(2)(3)(4);
Or:
#include <boost/assign/std/vector.hpp> using namespace boost::assign; ... std::vector<int> v; v += 1, 2, 3, 4;
Note that the latter syntax involves a slight overhead due to internal use of a std::deque. Therefore, for performance-critical code, consider using the std::vector initializer list directly, as suggested by Yacoby in the original question.
The above is the detailed content of How Can I Elegantly Initialize a std::vector with Hardcoded Elements in C ?. For more information, please follow other related articles on the PHP Chinese website!