首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向量SubScript超出范围,如何修复?

向量SubScript超出范围,如何修复?
EN

Stack Overflow用户
提问于 2018-04-12 15:57:17
回答 1查看 1.9K关注 0票数 0

我正在尝试颠倒向量的顺序。我编写了两个函数,并尝试在程序中调用它们。当我运行程序时,我得到一个错误:调试断言失败,第1795行,向量下标超出范围。我不知道如何修复它。

这是我的代码:

代码语言:javascript
复制
#include <iostream>
#include <vector>

using namespace std;


void reverse(vector<int>& intList, int first, int last)
{
while (first < 4)
{
    int temp = intList[first];
    intList[first] = intList[last];
    intList[last] = temp;
    first++;
    last--;
}
}
void print(vector<int>& intList, int size)
{
for (int i = 0; i < size; i++)
    cout << intList[i] << " ";
cout << endl;
}

int main()
{
    vector<int> intList;                        //Line 1
int i;                                      //Line 2

intList.push_back(13);                      //Line 3
intList.push_back(75);                      //Line 4
intList.push_back(28);                      //Line 5
intList.push_back(35);                      //Line 6


reverse(intList, 0, 4); 
cout << "Reversed array is: " << endl;
print(intList, 5);



return 0;
}
EN

回答 1

Stack Overflow用户

发布于 2018-04-12 16:10:40

while循环的第一次迭代中,在下面这行代码中:

代码语言:javascript
复制
intList[first] = intList[last];

您正在访问超出范围的intList[last]

顺便说一下,另一个问题是这一行:

代码语言:javascript
复制
while (first < 4)

应该这样写:

代码语言:javascript
复制
while (first <= last-1)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49790990

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档