Look at the code I posted above. To see for yourself, try and compile it. Compile it again by replacing "*(v + i)" with v[i] instead.
Like I said, do not confuse the random access operation(square brackets) to a direct address access operation(asterisk).
Try to remember addressing operations(pointers and arrays).
Consider passing a vector vs. passing an array to a parameter. I hope that you learned that in C, everything is passed by value. But this is not true in an array's case. If you pass an array to a parameter, you do not pass the value, you pass the address of the first element. So you do not make a copy.
Here is a sample code to back that theory:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
/*This is C, not C++*/
#include <stdio.h>
/*note that the parameter can be int [].*/
void modify(int* a){
int i;
for(i = 0; i < 10; ++i)
a[i] *= 2;
}
int main(void){
int a[10];
int i;
for(i = 0; i < 10; ++i)
a[i] = i;
/*prints "0 1 2 3 4 5 6 7 8 9"*/
for(i = 0; i < 10; ++i)
fprintf(stdout, "%d ", a[i]);
printf("\n");
modify(a);
/*prints "0 2 4 6 8 10 12 14 16 18"*/
for(i = 0; i < 10; ++i)
fprintf(stdout, "%d ", a[i]);
return 0;
}
| |
In C++, references were introduced so passing by value is not a problem for vectors anymore. But generally, if both arrays and vectors are passed to an argument in the same manner, vectors will be less efficient because of copying. Top of that, you may not be able to modify the values of the original vector passed to the function.
Vectors are provided to make it easy to perform array operations without the worry of getting many problematic exceptions(exceptions still occur in vectors though). If you are programming Java, it is pretty much an Arraylist.
If you program in lower levels, you'll see why, in some cases, arrays are preferred(because of address access) than other container classes.
EDIT:
I forgot to mention that operators in C++ are overloaded. The operator[]() of a vector works differently than an array's square brackets. Both, however, provides the same general purpose.
An array's square brackets can be used like this:
1 2 3
|
//some code
if(a[2] == *(a + 2))
//more code
| |