Last active
November 4, 2022 19:13
-
-
Save mshafae/697c2c169ebd5cdef9a3eb7d8c0bee1e to your computer and use it in GitHub Desktop.
CPSC 120 Demonstrate declaring and statically initializing a 2D std::array of string.
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/697c2c169ebd5cdef9a3eb7d8c0bee1e | |
#include <array> | |
#include <iostream> | |
#include <string> | |
#include <vector> | |
int main(int argc, char const *argv[]) { | |
std::vector<std::string> arguments{argv, argv + argc}; | |
// Arrays are row major order like a movie theater. This means the first index | |
// is the row and the second index is the column (or seat). All the types must | |
// be the same in an array. This is a declaration for a 2 x 4 array - 2 rows, | |
// 3 columns. Notice the double braces. | |
std::array<std::array<std::string, 3>, 2> sandwiches{ | |
{{"Pastrami on Rye", "Hot Dog", "Burrito"}, {"YES", "YES", "NO"}}}; | |
if (arguments.size() < 2) { | |
std::cout << "Please provide a sandwich name on the command line.\n"; | |
std::cout << "For example: ./a.out \"Pastrami on Rye\"\n"; | |
std::cout << "Exiting.\n"; | |
return 1; | |
} | |
int index{0}; | |
bool was_found{false}; | |
// Search for the sandwich passed on the command line | |
for (auto element : sandwiches) { | |
// row 0 has the sandwich names | |
if (sandwiches.at(0).at(index) == arguments.at(1)) { | |
was_found = true; | |
break; | |
} | |
index += 1; | |
} | |
// If the second row is "YES" then it is a sandwich, else it is not a | |
// sandwich. | |
bool is_sandwich{sandwiches.at(1).at(index) == "YES"}; | |
if (was_found && is_sandwich) { | |
std::cout << sandwiches.at(0).at(index) << " is considered a sandwich.\n"; | |
} else if (was_found && !is_sandwich) { | |
std::cout << sandwiches.at(0).at(index) | |
<< " is NOT considered a sandwich.\n"; | |
} else { | |
std::cout << "Sorry, I don't know about \"" << arguments.at(1) << "\"\n"; | |
std::cout << "I can't tell you if it is a sandwich or not.\n"; | |
std::cout << "Exiting.\n"; | |
return 1; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment