需要帮助理解“我的程序中的向量大于 max_size()”。 + 如何修复它[重复]

问题描述 投票:0回答:1

所以对于这个c++程序,我使用zybooks来运行这个程序,这是我之前第一次看到这个错误,但它只是给了我:向量大于max_size(),大于max_size()或什么都没有,就像通常它会说“程序没有产生输出”,但甚至没有产生。我只需要帮助了解这个错误到底是什么以及如何纠正这个问题。感谢您的阅读。

#include <iostream>
#include <vector>
using namespace std;

int main() {
   int numElements;
   int lowerBound;
   int upperBound;
   
   cin >> numElements;

   vector<int> numInts(numElements);
   for(int i = 0; i < numElements; ++i) {
      cin >> numInts.at(i);
      }
   cin >> lowerBound;
   cin >> upperBound;
   
   for(int i = 0; i < numElements; ++i) {
      if(numInts.at(i) >= lowerBound && numInts.at(i) <= upperBound) {
         cout << numInts.at(i) + ",";
      }
   }
   
   cout << endl;

   return 0;
}

鉴于它说我的向量大于 max_size(),我尝试编辑 i < numElements to i < numElements - 1 and that just produces no output, I've also used the size() method to no avail, and just changing numElements to no avail as well. Please excuse my inexperience, I'm yet to finish my semester of c++ programming I.

c++ stdvector
1个回答
0
投票

正如 drescherjm 所提到的,错误出现在最后一个 for 循环中:

cout << numInts.at(i) + ",";

您正在向 int 添加字符串文字。
你想做的是:

cout << numInts.at(i) << ",";

避免此类错误的最佳方法是使用带有警告的编译器。
我写了一个简短的代码审查,提供了资源,并重写了代码。
在编译器资源管理器上运行
希望它能激励您更多地了解这门语言!

© www.soinside.com 2019 - 2024. All rights reserved.