How to Initialize a std::vector with Hardcoded Elements Like an Array
Initializing a std::vector with a list of hardcoded elements might seem like a hassle compared to the simplicity of initializing an array. The common approach involves iteratively pushing elements onto the vector using push_back(). But is there a more elegant solution that mirrors the concise syntax of array initialization?
C 11's Elegant Solution
If your compiler supports C 11, the answer is a resounding yes. You can directly initialize a std::vector with a list of elements enclosed in {}:
<code class="cpp">std::vector<int> v = {1, 2, 3, 4};</code>
This syntax mimics array initialization and eliminates the need for loops or push_back().
Alternatives for Older Compilers
For compilers that don't support C 11, there are alternative methods:
Boost.Assign Library:
The Boost.Assign library provides a convenient way to initialize vectors using the following syntax:
<code class="cpp">#include <boost/assign/list_of.hpp> std::vector<int> v = boost::assign::list_of(1)(2)(3)(4);</code>
Operator Overloading:
You can overload the = operator to initialize a vector:
<code class="cpp">#include <boost/assign/std/vector.hpp> using namespace boost::assign; std::vector<int> v; v += 1, 2, 3, 4;</code>
Note that this method has some performance overhead compared to direct initialization, making it less suitable for performance-critical code.
The above is the detailed content of How to Initialize a std::vector with Specific Elements Without Loops?. For more information, please follow other related articles on the PHP Chinese website!