Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <sstream>
- #include <string>
- #include <memory>
- using namespace std;
- void removeNegative(unique_ptr<int[]>& ptr, int& n) {
- for (int i = 0; i < n; i++) {
- if (ptr[i] < 0) {
- for (int j = i; j < n - 1; j++) {
- ptr[j] = ptr[j + 1];
- }
- n--;
- i--;
- }
- }
- }
- void reverse(unique_ptr<int[]>& ptr, int& n) {
- int number, count = n / 2;
- for (int i = 0; i < count; i++) {
- number = ptr[i];
- ptr[i] = ptr[n - (1 + i)];
- ptr[n - (1 + i)] = number;
- }
- }
- int main() {
- string line;
- getline(cin, line);
- istringstream ss(line);
- unique_ptr<int[]> numbers = make_unique<int[]>(1000);
- int number, counter;
- for (counter = 0; counter < 1000 && ss >> number; ++counter) {
- numbers[counter] = number;
- }
- removeNegative(numbers, counter);
- if (counter == 0) {
- cout << "empty";
- }
- else {
- reverse(numbers, counter);
- for (int i = 0; i < counter; i++) {
- cout << numbers[i] << ' ';
- }
- }
- cout << endl;
- return 0;
- }
Advertisement
Comments
-
- ptr[j] = ptr[j + 1]; is an out of bounds access if it's only the last element in the array that is negative. the oob access can be avoided by changing the condition in for (int j = i; j < n; j++) to j < n-1
-
- while (ss >> number) { numbers[counter++] = number; } needs to limit the writes to numbers to prevent another oob access, for example using for (counter = 0; counter < 1000 && ss >> number; ++counter) numbers[counter] = number;
-
- Thank you so much! I fixed my code!
-
- thank you, always happy to help =)
Add Comment
Please, Sign In to add comment
Advertisement