Created
January 20, 2021 06:28
-
-
Save Loki-Astari/2189f23d331a4237cd80dd4df78e8c69 to your computer and use it in GitHub Desktop.
Examples of allocation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Version 1 | |
| // Your version | |
| // Two layers of indirection. | |
| std::string** myArray = new string*[size]; // call to new must be matched with delete. | |
| for (int loop; loop < size; ++loop) { | |
| myArray[loop] = new string; // call to new must be matched with delete. | |
| std::getline(std::cin, myArray[loop][0], '/'); | |
| std::getline(std::cin, myArray[loop][1]); | |
| } | |
| // Does not take into account exceptions. | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Version 2 | |
| // Single layer of indirection | |
| using Row = std::string[2]; | |
| Row* myArray = new Row[size]; // call to new must be matched with delete. | |
| for (int loop; loop < size; ++loop) { | |
| // No need for a new here. You have allocated size | |
| // objects that contain 2 strings. | |
| std::getline(std::cin, myArray[loop][0], '/'); | |
| std::getline(std::cin, myArray[loop][1]); | |
| } | |
| // Does not take into account exceptions. | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Version 3 | |
| // Single layer of indirection | |
| using Row = std::string[2]; | |
| using Array = std::vector<Row>; | |
| Array myArray{Row{}, size); // No dynamic allocation | |
| for (int loop; loop < size; ++loop) { | |
| // No need for a new here. You have allocated size | |
| // objects that contain 2 strings. | |
| std::getline(std::cin, myArray[loop][0], '/'); | |
| std::getline(std::cin, myArray[loop][1]); | |
| } | |
| // Exceptions handeled gracefully. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment