Skip to content

Instantly share code, notes, and snippets.

@mshafae
Created November 15, 2023 08:43
Show Gist options
  • Save mshafae/7dfcb98e197573a97b0766d48af7a6d2 to your computer and use it in GitHub Desktop.
Save mshafae/7dfcb98e197573a97b0766d48af7a6d2 to your computer and use it in GitHub Desktop.
Create a vector of objects. The object has multiple data members.
// Gist https://gist.github.com/mshafae/7dfcb98e197573a97b0766d48af7a6d2
// Filename cpsc120_food_class.cc
// CompileCommand clang++ -std=c++17 cpsc120_food_class.cc
// Create a vector of objects. The object has multiple data members.
#include <iostream>
#include <string>
#include <vector>
class Food {
private:
std::string name_;
bool is_sandwich_;
public:
Food(std::string name, bool is_sandwich)
: name_{name}, is_sandwich_{is_sandwich} {};
~Food(){};
std::string name() const { return name_; }
bool is_sandwich() const { return is_sandwich_; }
};
int main(int argc, char const* argv[]) {
std::vector<std::string> arguments{argv, argv + argc};
std::vector<Food> food_list{
Food{"Pastrami on Rye", true},
Food{"Hot Dog", false},
Food{"Ham and Cheese", true},
Food{"Burrito", false}
};
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;
}
bool was_found{false};
for (const auto& item : food_list) {
if (item.name() == arguments.at(1)) {
was_found = true;
if (item.is_sandwich()) {
std::cout << item.name() << " is considered a sandwich.\n";
} else {
std::cout << item.name() << " is NOT considered a sandwich.\n";
}
break;
}
}
if (!was_found) {
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