So i am messing with c++ learning some stuff and testing some stuff and i got few questions about vectors.
I will explain what i understand and if i am wrong please correct me
std::vector<char> myChars(25, 'v');
so in here i create a char array of size 25 and all fill with the char v.
I was reading my book and it saids vector's capacity will double if i reach the limit of the size. So now for instance i do
myChars.push_back('d'); This is where i add another char 'd' to the vector. In this case the size will become 26 but the capacity will become 25 x 2 which is 50?
Now another question, what if i did myChars.clear(); Now i delete all my values, will my vector's capacity return to 25? or it's still 50 empty spaces?
Now it also seems you cannot specify a characters in vectors, you can't make a vector array consist of k e i t h. You must use a for loop and even that it must be user input you can't hard code it. My question is, is there any way to get around that. That being said is there something like
myChars[0] = k, [1] = e etc...
I am also having trouble understanding iterators, can anyone explain it to me and how it that useuful?
1) Correct.
2) IIRC, yes that is correct.
3) The capacity will stay at 50. The size will become 0.
4) Use a string if you need an string. Alternatively, go find a compiler that supports C++0x and use an std::initializer_list
5) They are good for generic algorithms mainly. See stuff like std::for_each, std::find, etc.
You are literally just creating a vector of characters (it is not a string because it's not null-terminated). If you want a string, look into std string.
Generally, with a vector, do not worry too much about its capacity, unless you have good reason to care about its efficiency. Initially, you should care more about its size() and why you should or should not use a vector vs a list vs a map, etc... You should understand value-semantics and how that affects your vector if it contains objects, POD (plain-old-data), or pointers. You should understand why you can't have a vector of references.
The basic idea behind iterators is this: for a vector, the classical way of iteration is
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <vector>
#include <iostream>
using namspace std;
void tryVector() {
vector<int> v;
v.push_back( 5 );
v.push_back( 4 );
unsigned i, n= v.size();
for ( i=0; i<n; ++i )
cout << i << endl;
}
Line 11 and 12 is where the iteration happens. STL tries to standardize iterators so that Line 11 looks the same regardless of whether you are dealing with a map, list, or a vector. The iterator will hide that indexing i from you. An iterator will also keep you from reading out-of-bounds memory (if used properly). There are other reasons for iterators such as keeping state and its usefulness in copying and searching, but those things you will pick up as you see more examples.