Simplifying std::vector Initialization
When working with arrays in C , initialization is often straightforward:
int a[] = {10, 20, 30};
However, initializing a std::vector can be more cumbersome using the push_back() method:
std::vector<int> ints; ints.push_back(10); ints.push_back(20); ints.push_back(30);
C 11 Solution (with Support)
If your compiler supports C 11, you can utilize initializer lists:
std::vector<int> v = {1, 2, 3, 4};
This is available in GCC versions 4.4 and above.
Alternative Option (with Boost.Assign)
For older compilers, the Boost.Assign library offers a non-macro solution:
#include <boost/assign/list_of.hpp> ... std::vector<int> v = boost::assign::list_of(1)(2)(3)(4);
Or, using Boost.Assign's operators:
#include <boost/assign/std/vector.hpp> using namespace boost::assign; ... std::vector<int> v; v += 1, 2, 3, 4;
Keep in mind that Boost.Assign may have performance overhead compared to manual initialization.
The above is the detailed content of How Can I Simplify std::vector Initialization in C ?. For more information, please follow other related articles on the PHP Chinese website!