njp
njp

Reputation: 705

What do the brackets after a declaration of a vector object mean?

I come from a Python background, but I was reading up on the kind of objects and data structures available in the C++ standard library and I see that the declaration for say, a vector of strings:

vector<string> names(10);

Would indicate a vector object initialized to hold 10 objects of type string. My questions are:

Upvotes: 2

Views: 1921

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153802

There are two sorts of parameters to std::vector objects:

  1. There template arguments which are for std::vector the value type and the allocator types with the latter being defaulted. That is, std::vector<std::string> actually happens to be std::vector<std::string, std::allocator<std::string> >.
  2. There are run-time parameters passed as constructor arguments and std::vector<...> takes quite a few combinations of those. In the above quoted use the 10 is the number of initial elements given to the vector.

So, to answer your concrete questions:

  1. The string happens to be std::string and is nothing special at all. You can use any user-defined type which models certain concepts (e.g. the type needs to be CopyConstructible).
  2. The arguments in the parentheses are the contructor arguments (in the C++ context brackets are normally [ and ] but the term is ambiguous).
  3. string, well, actually std::string is not defined as a built-in type but it is a type from the standard C++ library. How the standard C++ library types are implemented is pretty much up to the C++ implementation, however, i.e., an implementation could choose to make it built-in (as long as it can still be used like a class type).

In C++ there are a few differences between built-in types and class types but with C++ 2011 it is gets pretty close to being able to create class types which behave like built-in types. The primary difference is that it is possible to take the address of certain members of class types while the same "members" are not accessible for built-in types. Another difference is that built-in types don't need to be declared (actually, they cannot be declared) while class types need to be declared and/or defined (depending on how these are used).

Upvotes: 3

Related Questions