-1
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    vector<int> v{1, 23, 4, 4, 5, 566, 67, 7, 87, 8, 8};

    size_t s = v.size();

    for (size_t i = 0; i < s; i++)
    {
        cout << v.at(i) << " ";
        v.pop_back();
    }

    return 0;
}

In the above code, I am straightaway getting out of bounds error without any output.
I expected that it would go out of bounds once it has printed half the vector, but apparently, that's not the case.

PS: There are no compile-time errors/warnings.

Appreciate any help!

  • 1
    A few things, don't use competitive coding sites to learn proper c++. You iterate over v to the begin length, but at the same time you are removing items with pop_back. How do you think that is going to work correctly? – Pepijn Kramer Jul 20 '22 at 11:58
  • How do you know you got out of bounds when `i == 0` ? – paolo Jul 20 '22 at 11:59
  • 2
    This is an excellent opportunity for you to learn how to use your debugger, to run this program one line at a time, and seeing for yourself how your expectations were absolutely 100% correct. This goes out of bounds and throws an exception halfway through the vector. You don't see any output? Well, see your C++ textbook for an explanation of what "buffering" and "flushing" means, when it comes to output. Knowing how to effectively use a debugger is a required skill for every C++ programmer. – Sam Varshavchik Jul 20 '22 at 11:59
  • 1
    Things you should unlearn : `using namespace std;`, `ios_base::sync_with_stdio(false);`, `cin.tie(NULL);` those hint at blindly copying code you don't understand (yet). Also have a look at range based for loops they're safer to use. – Pepijn Kramer Jul 20 '22 at 12:00
  • 1
    Also note that a program that compiles is not necessarily a program that is correct. – Pepijn Kramer Jul 20 '22 at 12:06
  • Output to `std::cout` is buffered by default, and output is only visible if data is transferred from the buffer to the output device (e.g. your monitor). With your compiler/library, the buffer is apparently large enough to hold all the data being written to `std::cout`, and the exception you're expecting (due to going out of bounds) is being thrown before any output is transferred from the buffer. Add some calls of `std::cout.flush()` in each iteration of the loop, and you'll see some expected output. – Peter Jul 20 '22 at 12:21

1 Answers1

0

Output is buffered. You can use std::endl or std::cout.flush() to force a flush of the stream:

for (size_t i = 0; i < s; i++)
{
    cout << v.at(i) << " ";
    cout.flush();
    v.pop_back();
}

PS: As mentioned in comments this code is bound to fail. You iterate till i < s but remove an element in each iteration. I suppose the code is merely to demonstrate the issue of missing output.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185