deque::end results in assertion failure

huangapple go评论132阅读模式
英文:

deque::end results in assertion failure

问题

以下是翻译好的部分:

"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."

"我正在编写一些需要使用结构体deque的代码。只有在经过了300行不断调试和过度工程化的代码之后,我才发现在这个代码中使用deque::end函数似乎不起作用。"

"any idea on how to solve the issue?"

"有没有解决这个问题的想法?"

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

"我想创建一个包含结构体deque的代码,但是在程序中使用deque::end函数时出现了错误。"

英文:

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

  1. #include <iostream>
  2. #include <deque>
  3. #define lli signed long long int
  4. using namespace std;
  5. typedef struct cityData
  6. {
  7. lli height;
  8. lli index;
  9. } cityData;
  10. int main()
  11. {
  12. deque<cityData> city;
  13. lli cityCount;
  14. cin >> cityCount;
  15. for (lli i = 1; i <= cityCount; i++)
  16. {
  17. cityData input;
  18. cin >> input.height;
  19. input.index = i;
  20. city.push_back(input);
  21. }
  22. cout << "firstIndex: " << city.begin()->index << endl;
  23. cout << "lastIndex: " << city.end()->index << endl;
  24. }

vvv Input vvv

  1. 10
  2. 9 2 8 3 7 2 8 2 9 1

vvv Output vvv

  1. firstIndex: 1
  2. error: cannot dereference out of range deque iterator
  3. 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.

答案1

得分: 2

deque::end() 返回指向最后一个元素之后的迭代器,不能被解引用。

你可以使用 deque::back() 来引用最后一个元素。(它返回一个元素的引用,而不是一个迭代器)

英文:

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)

huangapple
  • 本文由 发表于 2023年3月7日 22:07:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75663035.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定