views:

175

answers:

4

Can anybody explain me, what is use of vector class? My Professor mentioned about below sentence in the lecture. Template: Each vector has a class parameter that determines which object type will be used by that instance, usually called T. I don't understand what exactly class parameters means?

+13  A: 

The vector type in C++ is essentially a dynamic array. The class parameter is the type of the elements within the vector. For example

int arr[];  // Static C++ array with int elements
vector<int> v; // dynamic array with int elements

In this example int is the class parameter type.

EDIT

As several comments pointed out the choice of "class parameter" by your teacher is misleading. It's more correct to say "template parameter".

JaredPar
For clarity: the "class parameter" is (in essence) of type "class" (although it can be a primitive, so maybe "type")
Kendrick
I agree- calling it a class is misleading as you can pass primitives. This ain't Java.
DeadMG
It's really a template parameter anyway, and its type is `typename` IIRC.
strager
Agreed that the term chosen by the teacher is a bit odd but perhaps it's due to the class keyword as in template<class T>
Rune FS
@Rune FS: while the use of `class` is possible, it is recommend to use `typename` instead. `class` was used first because there was reluctance for the introduction of a new keyword, however it is both confusing (since you can pass built-in types or `struct`) and render the meaning of the keyword context dependent.
Matthieu M.
@Matthieu I totally agree. Personally I don't use <class> I've worked with plenty'o devs that thought it ment you could only pass a class. I don't call it a class argument either (except here for consistency with OPs use of terms) but just tried to point out that a person who write template<class T> might call T a class argument. I'm sorry if it seemed as a recommendation of that use
Rune FS
+2  A: 

The vector is defined as a template like:

template<typename T>
class Vector;

To use it you need to instantiate the template like:

Vector<char> myVector;

Instantiating a vector effectively creates a new class. which is equivalent to what you would get if you'd replaced every occurrence of T in the definition of the template with the class argument (in this case char)

So if we had a simple template

template<typename T>
class DataHolder{ 
public:
 T data
}

Instantiated like:

DataHolder<char> myChar;

Is equivalent to the class:

class DataHolder
{
public:
 char data;
}
Rune FS
Thanks, feels much better about question
Cool
+1  A: 

An example:

std::vector<int> v;

This declares a vector (dynamic array) of int elements. Initially it contains space for zero elements.

The web contains many resources about basic C++. See for example this page for more about STL vectors.

Michel de Ruiter
My professor gave me cplusplus.com website for reference but I think the website you gave is much easier to understand. Thanks
Cool