There was a problem. There is a vector of numbers arr , for example {1, -1, -1, 2, -2, 1, 1}. You need to write a function that will take this vector and remove elements that are opposite in sign if they stand side by side. I wrote this code here, but it doesn't work. Should return 1, and returns -2, why? Maybe someone knows the solution better? arr - the initial vector result_vec - the resultant vector, at the beginning is equal to arr

 #include<string> #include<iostream> #include<vector> std::vector<int> someFunc(std::vector<int>& arr); int main() { std::vector<int> d1 = { 1, -1, -1, 2, -2, 1, 1 }; std::vector<int> ans1 = someFunc(d1); for (int x : ans1) { std::cout << x << " "; // вывод результата } system("pause"); return 0; } std::vector<int> someFunc(std::vector<int>& arr) { std::vector<int> result = arr; // проход по элементам массива for (int i = 0; i < arr.size(); i++) { for (int j = 0; j < result.size() - 1; j++) { // здесь использую проход по result, т.к. каждый раз его размер уменьшается if ((arr[j] == -1 * arr[j + 1])) { result.erase(result.begin() + j); result.erase(result.begin() + j); } } } return result; } 
  • According to your description, the following elements {-1, 1, 1} should remain in the vector, since in this sub-sequence {-1, 2, -2, 1} -1 and 1 are not adjacent elements. They are separated by elements {2, -2} - Vlad from Moscow
  • iterations should occur while in the vector will not remain the opposite numbers next to each other. In your version, after another iteration, we get {1}. - Taras Sousse
  • Then the ambiguity of the solution takes place. Consider the sequence of pairs {{1, 'A'}, {2, 'B'}, {-2, 'C'}, {-1, 'D'}, {1, 'E'}}, where the opposite is considered signs of the first elements of couples. Then as a result, depending on the implementation, you can get a sequence consisting of an element of either {{1, 'A'}} or {{1, 'E'}} - Vlad from Moscow
  • Another question arises - what is to be done with the zeros around? Are they removed, or is it not considered to have opposite signs? - Vlad from Moscow
  • one
    Use in cycles only a call to the vector result. Why are there links to the arr vector at all ?! - Vlad from Moscow

1 answer 1

Not the most effective option, but nevertheless

 #include <vector> #include <algorithm> #include <iterator> #include <iostream> int main() { std::vector<int> a = { 1, -1, -1, 2, -2, 1, 1 }; auto p = [](int a, int b) { return a == -b; }; std::vector<int>::iterator it; while ((it = std::adjacent_find(a.begin(), a.end(), p)) != a.end()) do { it = a.erase(it, it + 2); it = std::adjacent_find(it, a.end(), p); } while (it != a.end()); std::copy(a.begin(), a.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; }