fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. #include <vector>
  5. #include <memory>
  6.  
  7. struct Animal
  8. { virtual void say() const {std::cout << "...\n";} };
  9.  
  10. struct Dog : Animal
  11. { virtual void say() const override {std::cout << "Woof\n";} };
  12.  
  13. struct Cat : Animal
  14. { virtual void say() const override {std::cout << "Meow\n";} };
  15.  
  16. struct Cow : Animal
  17. { virtual void say() const override {std::cout << "Moo\n";} };
  18.  
  19. using Animals = std::vector<std::unique_ptr<Animal>>;
  20.  
  21. Animals populate(std::istream& in)
  22. {
  23. Animals result;
  24. std::string animal;
  25. while(in >> animal)
  26. if (animal == "cow")
  27. result.emplace_back(new Cow);
  28. else if (animal == "cat")
  29. result.emplace_back(new Cat);
  30. else if (animal == "dog")
  31. result.emplace_back(new Dog);
  32. else
  33. result.emplace_back(new Animal);
  34. return result;
  35. }
  36.  
  37. int main()
  38. {
  39. std::istringstream input("cat cat cow dog cow foo");
  40. auto animals = populate(input);
  41. for(const auto& v: animals)
  42. v -> say();
  43. }
  44.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
Meow
Meow
Moo
Woof
Moo
...