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

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

Barbara Streisand
Release: 2024-12-25 13:01:09
Original
437 people have browsed it

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};
Copy after login

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);
Copy after login

C 11 Solution (with Support)

If your compiler supports C 11, you can utilize initializer lists:

std::vector<int> v = {1, 2, 3, 4};
Copy after login

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);
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template