Home >Backend Development >C++ >How Can I Simplify std::vector Initialization in C ?

How Can I Simplify std::vector Initialization in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-25 13:01:09440browse

How Can I Simplify std::vector Initialization in C  ?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn