Home > Backend Development > C++ > How Can I Elegantly Initialize a std::vector with Hardcoded Elements in C ?

How Can I Elegantly Initialize a std::vector with Hardcoded Elements in C ?

Susan Sarandon
Release: 2024-12-22 20:29:59
Original
153 people have browsed it

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

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

Or:

#include <boost/assign/std/vector.hpp>
using namespace boost::assign;
...
std::vector<int> v;
v += 1, 2, 3, 4;
Copy after login

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!

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