Quote:
|
Originally Posted by verizondude
Well seeing a vector as like being a massive array, wouldn't the user have to count the characters he/she would want to plug in?
|
For any data type that is a collection of elements, space needs to be allocated for the elements.
As an example, imagine a C-style string (array of
char, with the string's end marked by a zero). You need to allocate space for the string plus an additional
char element for the zero terminator. However, there are data structures that hide this sort of thing from you. The C++
string class is a good example. It allocates a block behind the scenes- say 20 characters- and tracks the current length of the string. It then allocates a larger block if it needs to, but this is all hidden from the user of the class.
A vector is similar. Say you have a struct defined like so:
struct g_Personalinfo
{
char firstname[10];
char lastname[15];
int age;
char school[30];
char subject[30];
int grade;
};
This does not actually create an instance. Rather, it only tells compiler what the type is composed of, so you can use it. I'm sure you already know this part. You need to create one or more instances, but you can create them either one at a time, or a bunch at once in an array:
g_Personalinfo singleItem;
g_Personalinfo arrayOfItems[100]; // room for 100 elements
If you use the array, you have to provide a subscript, just like with any other array access:
arrayOfItems[7].age = 19;
Now, this all works dandy until you exceed 100 students, or whatever type your array holds. It also means if you use less, you're wasting space. A vector is a better solution here. The syntax looks a bit funny, because vector is actually a template; think of a template as a layout, with an actual type filled in at runtime. It will look something like this:
// remember to #include <vector>
vector<g_Personalinfo> vectorOfItems(100); // 100 elements
You can then use it with array-style subscript notation, and you can 'push' elements on the end of the vector, or 'insert' them in the middle. If the vector is full when you add an element, it will resize itself. Thus, you don't need to worry so much about the size. There are methods for controlling how much space it reserves, and how it resizes itself, if you're paranoid it'll reserve too much (wasting space) or too little (meaning resizing happens more often, and resizing tends to be a slow operation).
The upshot of all this is that the user will not need to know in advance how many items they're inputting. The vector is sized to a default or specified size, and if this turns out to be too small, it will grow as needed.
Anyways, you can read all about vectors
right here (this reference in general is quite helpful and to-the-point, I find).