fork download
  1. #include <map>
  2. #include <vector>
  3. #include <string>
  4. #include <iostream>
  5. #include <stdexcept>
  6. typedef std::string Object;
  7.  
  8. int main() {
  9. std::vector<std::string> names;
  10. names.push_back(std::string("A"));
  11. names.push_back(std::string("A"));
  12. names.push_back(std::string("B"));
  13. names.push_back(std::string("C"));
  14. names.push_back(std::string("A"));
  15.  
  16. Object* ptr_A = new Object("APPLE");
  17. Object* ptr_B = new Object("BANANA");
  18. Object* ptr_C = new Object("CARROT");
  19.  
  20. std::vector<Object*> objects;
  21.  
  22. // ANSWER
  23. typedef std::map<std::string, Object*>::iterator iterator;
  24. typedef std::pair<std::string, Object*> value_type;
  25. std::map<std::string, Object*> lookup; //or maybe unordered_map
  26. lookup.insert(value_type("A", ptr_A));
  27. lookup.insert(value_type("B", ptr_B));
  28. lookup.insert(value_type("C", ptr_C));
  29.  
  30. for(int i=0; i<names.size(); ++i) {
  31. iterator iter = lookup.find(names[i]);
  32. if (iter == lookup.end())
  33. throw std::runtime_error("invalid name in file");
  34. objects.push_back(iter->second);
  35. }
  36. // END ANSWER
  37.  
  38. for(int i=0; i<objects.size(); ++i)
  39. std::cout << *objects[i] << '\n';
  40. }
Success #stdin #stdout 0.01s 2864KB
stdin
Standard input is empty
stdout
APPLE
APPLE
BANANA
CARROT
APPLE