If I want to build a very simple array like
int myArray[3] = {1,2,3};
Should I use std::array
instead ?
std::array<int, 3> a = {{1, 2, 3}};
What are the advantages of using std::array over usual ones? Is it more performant ? Just easier to handle for copy/access ?
There is a myth that for run-time speed, one should use arrays. A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program.
It will provide a value like semantics equally to the other C++ containers. A std::array should have same runtime performance as a c-style array.
Difference between std::vector and std::array in C++ As array is fixed size, once initialized can't be resized. Vector occupies more memory. Array is memory efficient data structure. Vector takes more time in accessing elements.
Arrays have a better performance than maps since you know which element you want to access, as much as maps have constant access, arrays have instant access if called by their index.
What are the advantages of using
std::array
over usual ones?
It has friendly value semantics, so that it can be passed to or returned from functions by value. Its interface makes it more convenient to find the size, and use with STL-style iterator-based algorithms.
Is it more performant ?
It should be exactly the same. By definition, it's a simple aggregate containing an array as its only member.
Just easier to handle for copy/access ?
Yes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With