the following code fills the vector with 10 values in first for loop. in second for loop i want the elements of vector to be printed. The output is till the cout statement before the j loop.Gives error of vector subscript out of range.
下面的代码在第一个循环中填充了10个值的向量。在第二个for循环中,我想要打印出向量的元素。输出是在j循环之前的cout语句。在范围内给出矢量下标的错误。
#include "stdafx.h"
#include "iostream"
#include "vector"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{ vector<int> v;
cout<<"Hello India"<<endl;
cout<<"Size of vector is: "<<v.size()<<endl;
for(int i=1;i<=10;++i)
{
v.push_back(i);
}
cout<<"size of vector: "<<v.size()<<endl;
for(int j=10;j>0;--j)
{
cout<<v[j];
}
return 0;
}
2 个解决方案
#1
8
Regardless of how do you index the pushbacks your vector contains 10 elements indexed from 0
(0
, 1
, ..., 9
). So in your second loop v[j]
is invalid, when j
is 10
.
不管你如何索引,你的向量包含10个元素从0(0,1,…)所以在第二个循环中v[j]是无效的,当j是10时。
This will fix the error:
这将修正错误:
for(int j = 9;j >= 0;--j)
{
cout << v[j];
}
In general it's better to think about indexes as 0
based, so I suggest you change also your first loop to this:
一般来说,最好把索引设为0,所以我建议你也改变一下你的第一个循环:
for(int i = 0;i < 10;++i)
{
v.push_back(i);
}
#2
5
v
has 10
element, the index starts from 0
to 9
.
v有10个元素,指数从0到9。
for(int j=10;j>0;--j)
{
cout<<v[j]; // v[10] out of range
}
you should update for
loop to
您应该更新for循环。
for(int j=9; j>=0; --j)
// ^^^^^^^^^^
{
cout<<v[j]; // out of range
}
Or use reverse iterator to print element in reverse order
或者使用反向迭代器以相反的顺序打印元素。
for (auto ri = v.rbegin(); ri != v.rend(); ++ri)
{
std::cout << *ri << std::endl;
}
#1
8
Regardless of how do you index the pushbacks your vector contains 10 elements indexed from 0
(0
, 1
, ..., 9
). So in your second loop v[j]
is invalid, when j
is 10
.
不管你如何索引,你的向量包含10个元素从0(0,1,…)所以在第二个循环中v[j]是无效的,当j是10时。
This will fix the error:
这将修正错误:
for(int j = 9;j >= 0;--j)
{
cout << v[j];
}
In general it's better to think about indexes as 0
based, so I suggest you change also your first loop to this:
一般来说,最好把索引设为0,所以我建议你也改变一下你的第一个循环:
for(int i = 0;i < 10;++i)
{
v.push_back(i);
}
#2
5
v
has 10
element, the index starts from 0
to 9
.
v有10个元素,指数从0到9。
for(int j=10;j>0;--j)
{
cout<<v[j]; // v[10] out of range
}
you should update for
loop to
您应该更新for循环。
for(int j=9; j>=0; --j)
// ^^^^^^^^^^
{
cout<<v[j]; // out of range
}
Or use reverse iterator to print element in reverse order
或者使用反向迭代器以相反的顺序打印元素。
for (auto ri = v.rbegin(); ri != v.rend(); ++ri)
{
std::cout << *ri << std::endl;
}