Created
June 22, 2017 08:59
-
-
Save amigo421/91f32859bf7ceabd8de3b1f9e405a62f to your computer and use it in GitHub Desktop.
school example of dynamic memory management
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
| #include <iostream> | |
| #include <algorithm> | |
| #include <iterator> | |
| #include <numeric> | |
| int* array_append(int *arr, unsigned int &size, int value) { | |
| int *new_arr = new int[size + 1]; | |
| std::memcpy(new_arr, arr, size * sizeof(*new_arr)); | |
| if (size && arr != nullptr) | |
| delete[] arr; | |
| new_arr[size] = value; | |
| ++size; | |
| return new_arr; | |
| } | |
| int* array_insert(int *arr, unsigned int &size, unsigned int index, int value) { | |
| if (size == 0 || index >= size) | |
| return array_append(arr, size, value); | |
| int *new_arr = new int[size + 1]; | |
| std::memcpy(new_arr, arr, index * sizeof(int)); | |
| std::memcpy(new_arr + index + 1, | |
| arr + index, | |
| (size - index) * sizeof(int)); | |
| if (size && arr != nullptr) | |
| delete[] arr; | |
| new_arr[index] = value; | |
| ++size; | |
| return new_arr; | |
| } | |
| int main() | |
| { | |
| // task A | |
| int value; | |
| int *arr = nullptr; | |
| unsigned int size = 0; | |
| while (std::cin >> value && value != -1) | |
| arr = array_append(arr, size, value); | |
| unsigned int count = 0; | |
| std::copy_if(arr, arr + size, std::ostream_iterator<int>(std::cout, " "), [&count](auto value) { | |
| return value > 10 && ++count; | |
| }); | |
| delete[] arr; | |
| std::cout << '\n' << count << '\n'; | |
| // Task B | |
| unsigned int N = 0; | |
| std::cin >> N; | |
| int *arr = new int[N]; | |
| std::copy_n(std::istream_iterator<int>(std::cin), | |
| N, | |
| arr); | |
| arr = array_insert(arr, N, N / 2, std::accumulate(arr, arr + N, 0)); | |
| std::copy(arr, arr + N, std::ostream_iterator<int>(std::cout, " ")); | |
| delete[] arr; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment