0
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector <pair<int,int>> s1= {{1,2}, {2,3}, {4,5}, {5,6}};
    int x= 10, count; 
    while (!s1.empty() && s1.back().first <= x )
    {
        count= count + s1.back().second;
        if (s1.back().first== x && s1.back().second== -1)
        {
            ++count; 
        }
        s1.pop_back();
    }
    for (int i=0; i<4; ++i)
    {
        cout << s1[i].first << " " << s1[i].second << endl;
    }
}

When I run this program, it outputs all the elements originally in the vector s1. Shouldn't the vector be empty due to the use of pop_back()?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
sam
  • 101
  • 1
  • 4
  • 2
    In an empty vector *all* indexes (even `0`) will be out of bounds. If you use out of bounds indexes you have undefined behavior. End of story, really. – Some programmer dude Jun 05 '20 at 21:56
  • you assume that the vector has 4 elements, try to use `s1.size()` instead – 463035818_is_not_an_ai Jun 05 '20 at 21:56
  • You have undefined behavior (uninitialized `count`, accessing 4 elements of array). The program can do whatever it wants to, including returning the "ghosts" of deleted array elements. – rsjaffe Jun 05 '20 at 21:58

1 Answers1

2

while (!s1.empty() && s1.back().first <= x )

Logically equates to this:

 while (!s1.empty())

Because all the first elements in the vector are smaller than 10, which means the while terminates only when the vector is empty.

Then, in the for loop, you access out of bounds, causing undefined behavior.

Simply change the for loop to this:

 for (int i=0; i<s1.size(); ++i)
 {
     cout << s1[i].first << " " << s1[i].second << endl;
 }

You could also use std::for_each() from the <algorithm> header:

std::for_each(s1.begin(), s1.end(), [](auto const &it) {
    cout << it.first << " " << it.second << endl;
});
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Tony Tannous
  • 14,154
  • 10
  • 50
  • 86
  • I got the feeling that the OP was shocked that they could still view the items even though the vector was empty / did not understand why the program did not crash or complain about this. – drescherjm Jun 05 '20 at 22:04
  • 1
    @drescherjm every c\c++ programmer experiences an undefined behavior at some point :) – Tony Tannous Jun 05 '20 at 22:12
  • 2
    @Bhavika maybe you should ask a new question about your code and what you wanted it to do. This question is really about the undefined behavior of accessing elements of an empty vector it is both answered and closed as a duplicate. I can tell you that I don't understand exactly what you wanted with your code. – drescherjm Jun 05 '20 at 22:41
  • 1
    A [range-based `for` loop](https://en.cppreference.com/w/cpp/language/range-for) would be better: `for(auto &it : s1) { cout << it.first << " " << it.second << endl; };` – Remy Lebeau Jun 06 '20 at 00:44