0

I was coding some code which needs a deque of structs. Only after 300 lines of repeatedly debugged code and excessive over-engineering, I found out that using the deque::end function somehow doesn't work in this code.

Below is a simplified version of the code:

vvv code vvv

#include <iostream>
#include <deque>
#define lli signed long long int

using namespace std;

typedef struct cityData
{
    lli height;
    lli index;

} cityData;

int main()
{
    deque<cityData> city;

    lli cityCount;
    cin >> cityCount;

    for (lli i = 1; i <= cityCount; i++)
    {
        cityData input;
        cin >> input.height;
        input.index = i;

        city.push_back(input);
    }

    cout << "firstIndex: " << city.begin()->index << endl;
    cout << "lastIndex: " << city.end()->index << endl;
}

vvv Input vvv

10
9 2 8 3 7 2 8 2 9 1

vvv Output vvv

firstIndex: 1

error: cannot dereference out of range deque iterator
code terminated with exit code 3.

any idea on how to solve the issue?

I wanted to create a code which contains a deque of structs, however, an error occured when I used the function deque::end on the program.

Evg
  • 25,259
  • 5
  • 41
  • 83
  • `end()` in the standard library is defined as one element past the last valid element. – drescherjm Mar 07 '23 at 14:08
  • No tags in the title please. There is a special field for tags. – Evg Mar 07 '23 at 14:09
  • 3
    you should not `#define lli`, never. – apple apple Mar 07 '23 at 14:10
  • @drescherjm oh shoot, thanks for the info, appreciate it! – Oportunitas Mar 07 '23 at 14:14
  • Side notes: (1) [using namespace std](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice), (2) [#define lli signed long long int](https://stackoverflow.com/questions/67649609/using-preprocessing-directive-define-for-long-long) – wohlstad Mar 07 '23 at 14:15

1 Answers1

1

deque::end() returns an iterator to an element past the last element, and it mustn't be dereferenced.

You can use deque::back() to refer to the last element. (This returns a reference to an element, not an iterator)

MikeCAT
  • 73,922
  • 11
  • 45
  • 70