Hey,new to stl, in c array, we can declare an array like

int a[]={2,4,5,6,7,7}

how can u do it for a vector without pushing back n times???

Dani AI

Generated

Short answer: no need to call push_back repeatedly. There are several concise idioms depending on the C++ standard and where the source data comes from.

As noted by , constructing from a range is idiomatic; in modern C++ prefer std::begin/std::end instead of manual sizeof arithmetic:

std::vector<int> v(std::begin(a), std::end(a));

C++11 and later add brace-init lists, which are the simplest when literal values are known:

std::vector<int> v = {2, 4, 5, 6, 7, 7};

For repeating values the dedicated constructor is handy:

std::vector<int> v(6, 7); // six elements, each == 7

When an array is passed into a function, it decays to a pointer so sizeof no longer yields element count; to avoid that pitfall use a template that captures the array size:

template<typename T, std::size_t N>
std::vector<T> make_vector(const T (&arr)[N]) {
    return std::vector<T>(std::begin(arr), std::end(arr));
}

Performance notes: the vector range constructor allocates once and copies all elements. If building incrementally from input, call reserve(expected_count) first to avoid repeated reallocations, and prefer emplace_back when constructing complex objects in-place. As mentioned, Boost::Assign used to give compact syntax before C++11; with brace-init and std::initializer_list that need is largely gone.

Caution: when constructing from raw pointers or arrays, ensure the source remains valid during construction and that iterator types meet constructor requirements (input/forward iterators, etc.).

Recommended Answers

All 3 Replies

Make an algorithm.

You can do something like this:

int myints[] = {16,2,77,29};
  vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );

Hey,new to stl, in c array, we can declare an array like

int a[]={2,4,5,6,7,7}

how can u do it for a vector without pushing back n times???

C++0x has extended initializer lists, but current standard C++ doesn't allow it for the vector class without tricks like siddhant3s'. Boost::Assign can make it shorter than a bunch of push_back calls and save you a dummy variable at the cost of Boost. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.