Advertisement
Spocoman

02. Remove Negatives and Reverse

Feb 9th, 2024 (edited)
865
0
Never
4
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include <iostream>
  2. #include <sstream>
  3. #include <string>
  4. #include <memory>
  5.  
  6. using namespace std;
  7.  
  8. void removeNegative(unique_ptr<int[]>& ptr, int& n) {
  9.     for (int i = 0; i < n; i++) {
  10.         if (ptr[i] < 0) {
  11.             for (int j = i; j < n - 1; j++) {
  12.                 ptr[j] = ptr[j + 1];
  13.             }
  14.             n--;
  15.             i--;
  16.         }
  17.     }
  18. }
  19.  
  20. void reverse(unique_ptr<int[]>& ptr, int& n) {
  21.     int number, count = n / 2;
  22.     for (int i = 0; i < count; i++) {
  23.         number = ptr[i];
  24.         ptr[i] = ptr[n - (1 + i)];
  25.         ptr[n - (1 + i)] = number;
  26.     }
  27. }
  28.  
  29. int main() {
  30.     string line;
  31.     getline(cin, line);
  32.  
  33.     istringstream ss(line);
  34.  
  35.     unique_ptr<int[]> numbers = make_unique<int[]>(1000);
  36.  
  37.     int number, counter;
  38.  
  39.     for (counter = 0; counter < 1000 && ss >> number; ++counter) {
  40.         numbers[counter] = number;
  41.     }
  42.  
  43.     removeNegative(numbers, counter);
  44.  
  45.     if (counter == 0) {
  46.         cout << "empty";
  47.     }
  48.     else {
  49.         reverse(numbers, counter);
  50.         for (int i = 0; i < counter; i++) {
  51.             cout << numbers[i] << ' ';
  52.         }
  53.     }
  54.  
  55.     cout << endl;
  56.     return 0;
  57. }
Advertisement
Comments
  • Vvardenfell
    279 days (edited)
    # text 0.20 KB | 1 0
    1. 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
  • Vvardenfell
    279 days
    # text 0.22 KB | 1 0
    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;
Add Comment
Please, Sign In to add comment
Advertisement