I'm learning C++ and recently got into this problem:
reverse sequence of positive integers that are coming from std::cin, sequence ends when -1 is approached. This '-1' should not be a part of sequence. Print out reversed sequence, it also must end with -1.
So, I've written pretty straightforward code that does exactly that, it might be not the best in terms of performance, as if I counted right, overall O(N^2 / 2).
int n = 0;
vector<int> numbers; //placeholder vector for input
while (n != -1) {
cin >> n;
numbers.push_back(n);
}
numbers.erase(numbers.end() - 1); // -1 should not be the part of the vector, so I erase it
n = numbers.size() - 1;
for (int i = 0; i < n / 2; ++i) { //swapping
int tmp = numbers[i];
numbers[i] = numbers[n - i];
numbers[n - i] = tmp;
}
for (auto a : numbers) //printing out
cout << a << " "; //each integer in input and output is separated by spacebar
cout << -1; //last element should be '-1'
Unfortunately, this code passes 4/10 test cases which was quite shocking for me.
I would be very grateful if anyone could give me a hint of what is wrong with my code or any generic advices about performance.
Aucun commentaire:
Enregistrer un commentaire