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; }