Original from: https://shendrick.net/Coding%20Tips/2015/03/15/cpparrayvsvector.html @Seth Hendrick
Original Article This article was: https://shendrick.net/Coding%20Tips/2015/03/15/cpparrayvsvector. html @Seth Hendrick
C-Style Array
Assignment
int myArray[3] = {1, 2, 3};
Arrays and pointers
a[1]
Equivalent to*(a+1)
std::cout << std::boolalpha << (myArray[0] == *myArray) << std::endl;
std::cout << std::boolalpha << (myArray[1] == *(myArray + 1) << std::endl;
// Outputs:
// true
// true
Array size
int myArray[5] = {1, 2, 3, 4, 5};
size_t arraySize = sizeof(myArray) / sizeof(int);
std::cout << "C-style array size: " << arraySize << std::endl;
// Outputs:
// C-style array size: 5
#include <iostream>
void printSize(int someArray[5]) {
std::cout << sizeof(someArray)/sizeof(int) << std::endl;
}
int main() {
int myArray[5] = {1, 2, 3, 4, 5};
printSize(myArray);
}
// Outputs:
// 2
The second example, the function does not return the correct size of the array. This is because the array as an input parameter, is passed in a size_t
size of a pointer, in particular the size of the machine may be 8 bytes, the int
type size is four words section, since the second example corresponds to sizeof(size_t) / sizeof(int)
the output 2 of the result.
Traversal cycle
A section similar to the above, in the same scope, the array can be in C ++ through the loop 11,
int main() {
int myArray[5] = {1, 2, 3, 4, 5};
for (int &i : myArray) {
std::cout << i << ", " << std::endl;
}
}
But when the array is passed as a function of other variables, failed traversal cycle
#include <iostream>
void printElements(int someArray[5]) {
for (int &i : someArray) {
std::cout << i << ", " << std::endl;
}
}
int main() {
int myArray[5] = {1, 2, 3, 4, 5};
printElements(myArray);
}
The reason is the same, is passed a pointer.
std::array
std::array
C is an array after a package, you must determine the size of the array at compile time.
Declare an array
#include <array>
#include <iostream>
void printElements(const std::array<int, 5> &someArray) {
for (const int &i : someArray) {
std::cout << i << ", " << std::endl;
}
std::cout << "Size: " << someArray.size() << std::endl;
}
int main() {
std::array<int, 5> myArray = {1, 2, 3, 4, 5};
printElements(myArray);
}
// Outputs:
// 1,
// 2,
// 3,
// 4,
// 5,
// Size: 5