Skip to content

Instantly share code, notes, and snippets.

@mshafae
Last active September 27, 2022 03:55
Show Gist options
  • Save mshafae/29e77a62a20852cb0925aeb5ab840a77 to your computer and use it in GitHub Desktop.
Save mshafae/29e77a62a20852cb0925aeb5ab840a77 to your computer and use it in GitHub Desktop.
Working with C++ arrays (not C arrays).
// Gist https://gist.github.com/29e77a62a20852cb0925aeb5ab840a77
#include <array>
#include <iostream>
using namespace std;
int main(int argc, char const* argv[]) {
std::array<int, 5> even_numbers{2, 4, 6, 8, 10};
for(int index = 0; index < even_numbers.size(); index++){
std::cout << "The even number at " << index << " is " << even_numbers.at(index)
<< ".\n";
}
array<int, 5> odd_numbers;
for(int index = 0, counter = 1; index < even_numbers.size(); index++, counter += 2){
odd_numbers.at(index) = counter;
}
int index{0};
for(int number : odd_numbers){
std::cout << "The odd number at " << index << " is " << number << ".\n";
index = index + 1;
}
// We can catch the error and handle it gracefully.
try{
cout << "The even number at " << 123456 << " is " << even_numbers.at(123456)
<< ".\n";
}catch(std::exception const& e){
cout << "We tried to find something outside the bounds of our array and we nearly crashed.\n";
cout << e.what() << "\n";
}
// This will cause the program to fail.
cout << "The even number at " << 123456 << " is " << even_numbers.at(123456)
<< ".\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment