7

I have a class field which is a std::vector. I know how many elements I want this vector to contain: N. How do I initialize the vector with N elements?

4
  • Are you referring to the initial size or the initial capacity? Commented Mar 14, 2011 at 4:15
  • @Emile. Initial size I guess. I don't quite follow. Are you referring to using reserve() to reserve capacity? Commented Mar 14, 2011 at 4:18
  • Yes, I am. Let me put it in another way: Do you want your vector to initially have N elements, or do you want your vector to be able to grow to N elements without reallocation? Commented Mar 14, 2011 at 4:21
  • @Emile. Initially have N elements, answers below by James and Jerry were exactly what I was looking for. Commented Mar 14, 2011 at 4:26

3 Answers 3

9

std::vector has a constructor declared as:

vector(size_type N, const T& x = T());

You can use it to construct the std::vector containing N copies of x. The default value for x is a value initialized T (if T is a class type with a default constructor then value initialization is default construction).

It's straightforward to initialize a std::vector data member using this constructor:

struct S {
    std::vector<int> x;
    S() : x(15) { }
} 
Sign up to request clarification or add additional context in comments.

3 Comments

You've already alluded to the fact that the N elements are copy-constructed. I don't think there's a way to create a vector in such a way that the elements are default constructed (which is how I interpret the question title), although in C++0x it can be done post-construction using emplace_back.
@Ben: Well, one element is default constructed here :-). In C++0x, the constructor I mention is actually two constructors: vector(size_type N) and vector(size_type N, const T& x). The first one value initializes the N elements and does not call any copy constructors. The resize function has similarly been split into two overloads.
The parameter is default constructed, but it isn't a vector element at all. Good to know that in C++0x there's now two implementations instead of a default argument.
8
class myclass {
   std::vector<whatever> elements;
public:
   myclass() : elements(N) {}
};

Comments

1

All the constructors that allow you to specify a size also invoke the element's constructor. If efficiency is paramount, you can use the reserve() member function to reserve the size. This does not actually create any elements, so it is more efficient. In most cases, though, supplying the size through the vector constructor is just fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.