Last active
November 17, 2020 00:30
-
-
Save Adobe-Android/011fcbf4728a8620c7ee70615321f78d to your computer and use it in GitHub Desktop.
C-style array vs. C++ std::array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <array> | |
struct Person { | |
char name[256]; | |
}; | |
void print_name(Person* person_ptr) { | |
std::cout << person_ptr->name << '\n'; | |
} | |
void print_name(std::array<Person, 3> person_ptr) { | |
std::cout << person_ptr[0].name << '\n'; | |
} | |
void print_name(Person* people, size_t num_people) { | |
for (size_t i = 0; i < num_people; i++) { | |
std::cout << people[i].name << '\n'; | |
} | |
} | |
void print_name(std::array<Person, 3> people, size_t num_people) { | |
for (size_t i = 0; i < num_people; i++) { | |
std::cout << people[i].name << '\n'; | |
} | |
} | |
int main() { | |
Person famous_people_arr[] = { "Hugh Jackman", "Tom Hanks", "Emma Watson" }; | |
// C++11 | |
std::array<Person, 3> famous_people_std_arr = { "Hugh Jackman", "Tom Hanks", "Emma Watson" }; | |
// C++17 - Class template argument deduction | |
std::array famous_people_std_arr_17 { "Hugh Jackman", "Tom Hanks", "Emma Watson" }; | |
print_name(famous_people_arr); | |
print_name(famous_people_std_arr); | |
std::cout << '\n'; | |
print_name(famous_people_arr, sizeof(famous_people_arr) / sizeof(Person)); | |
std::cout << '\n'; | |
print_name(famous_people_std_arr, famous_people_std_arr.size()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment