Skip to content

Instantly share code, notes, and snippets.

@mshafae
Last active December 13, 2023 23:18
Show Gist options
  • Save mshafae/eb239941e0171dcf564d91a3f75c64a7 to your computer and use it in GitHub Desktop.
Save mshafae/eb239941e0171dcf564d91a3f75c64a7 to your computer and use it in GitHub Desktop.
Create a vector of vectors, the inner vectors contain strings
// Gist https://gist.github.com/mshafae/eb239941e0171dcf564d91a3f75c64a7
// Filename cpsc120_2D_vector.cpp
// CompileCommand clang++ -std=c++17 cpsc120_2D_vector.cpp
// Create a vector of vectors, the inner vectors contain strings
// Note that C++ is row major order.
#include <iostream>
#include <string>
#include <vector>
int main(int argc, char const *argv[]) {
std::vector<std::string> arguments{argv, argv + argc};
// Vectors 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 vector. This is a declaration for a 2 x 3
// vector - 2 rows, 3 columns. Notice the double braces.
// The table below looks like this:
// | "Pastrami on Rye" | "Hot Dog" | "Burrito" |
// | "YES" | "YES" | "NO" |
std::vector<std::vector<std::string>> 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
// row 0 has the sandwich names
// Instead of this
// std::vector<std::string> row = sandwiches.at(0);
// You can use auto
auto row = sandwiches.at(0);
// The compiler can deduce that element is a std::string
for (const auto& element : row) {
if (element == 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{false};
if (was_found) {
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