fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. // We have a house that has an address
  5. struct House
  6. {
  7. std::string address;
  8. };
  9.  
  10. // And a region that contains houses
  11. struct Region
  12. {
  13. House* houses = nullptr;
  14. unsigned num_houses = 0;
  15. };
  16.  
  17. // This is how we might add a house to a region:
  18. void add_house(Region& region, const std::string& address)
  19. {
  20. House* new_houses = new House[region.num_houses + 1];
  21.  
  22. for (unsigned i = 0; i < region.num_houses; ++i)
  23. new_houses[i] = region.houses[i];
  24.  
  25. new_houses[region.num_houses].address = address;
  26.  
  27. delete [] region.houses;
  28.  
  29. region.houses = new_houses;
  30. ++region.num_houses;
  31. }
  32.  
  33. void show_region(const Region& region)
  34. {
  35. std::cout << "This region contains houses at the following addresses:\n";
  36. for (unsigned i = 0; i < region.num_houses; ++i)
  37. {
  38. std::cout << '\t' << region.houses[i].address << '\n';
  39. }
  40. }
  41.  
  42. int main()
  43. {
  44. Region region;
  45.  
  46. std::cout << "Enter addresses to add houses to a region (or an empty line to stop):\n";
  47. std::string line;
  48. while (std::cout << "> ", std::getline(std::cin, line) && !line.empty())
  49. add_house(region, line);
  50.  
  51. show_region(region);
  52.  
  53. delete [] region.houses ; // normally this would be done in a destructor.
  54. }
Success #stdin #stdout 0s 3480KB
stdin
1 Country Oak Lane
319 N 7th Street
19350 Park Avenue
stdout
Enter addresses to add houses to a region (or an empty line to stop):
> > > > This region contains houses at the following addresses:
	1 Country Oak Lane
	319 N 7th Street
	19350 Park Avenue