Home >Backend Development >C++ >How Can I Elegantly Initialize Vectors in C ?

How Can I Elegantly Initialize Vectors in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-21 11:33:14176browse

How Can I Elegantly Initialize Vectors in C  ?

Simplifying Vector Initialization: Elegant Hardcoding Options

Creating custom initializers for arrays is a standard and straightforward practice. However, when it comes to vectors, finding a similar mechanism can be a bit trickier. The inherent question is whether there exists a method to initialize vectors as cleanly as arrays. Let's explore the solutions.

The standard approach, as you mentioned, involves push_back operations:

std::vector<int> ints;
ints.push_back(10);
ints.push_back(20);
ints.push_back(30);

While this method serves its purpose, it doesn't match the elegance of array initialization.

C 11's Brace-Enclosed Initialization

With C 11 and compatible compilers like GCC 4.4, you can embrace brace-enclosed initialization for vectors:

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

This syntax provides a concise and explicit way to initialize vectors.

Boost.Assign Library

Another alternative is to utilize the Boost.Assign library. It offers various techniques for vector initialization:

Using list_of:

#include <boost/assign/list_of.hpp>
...
std::vector<int> v = boost::assign::list_of(1)(2)(3)(4);

Using = notation:

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

However, note that Boost.Assign carries some performance overhead due to its underlying mechanisms. For performance-sensitive code, consider the push_back approach.

The above is the detailed content of How Can I Elegantly Initialize Vectors 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