Created
November 13, 2023 21:25
-
-
Save mshafae/ff7818bd3514ad0539e90b5d2f8933b3 to your computer and use it in GitHub Desktop.
Working with C++ vectors.
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
// Gist https://gist.github.com/mshafae/ff7818bd3514ad0539e90b5d2f8933b3 | |
// Filename cpsc120_vector.cc | |
// CompileCommand clang++ -std=c++17 cpsc120_vector.cc | |
// Working with C++ vectors. | |
#include <iostream> | |
#include <vector> | |
int main(int argc, char const* argv[]) { | |
std::vector<int> 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"; | |
} | |
std::vector<int> odd_numbers; | |
// Example of a for loop with two different counters | |
for (int index = 0, counter = 1; index < even_numbers.size(); | |
index++, counter += 2) { | |
// Add numbers to the back of the vector. | |
odd_numbers.push_back(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 { | |
std::cout << "The even number at " << 123456 << " is " | |
<< even_numbers.at(123456) << ".\n"; | |
} catch (std::exception const& e) { | |
std::cout | |
<< "We tried to find something outside the bounds of our array and we " | |
"nearly crashed.\n"; | |
std::cout << e.what() << "\n"; | |
} | |
// flush everything out to stdout. | |
std::cout << std::flush; | |
// This will probably NOT cause the program to fail but it doesn't make sense. | |
std::cout << "The even number at " << 123456 << " is " << even_numbers[123456] | |
<< ".\n"; | |
// flush everything out to stdout. | |
std::cout << std::flush; | |
// This will cause the program to fail. | |
std::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