C++ 向量下标超出范围。比较向量的元素
我有一个像这样的向量C++ 向量下标超出范围。比较向量的元素,c++,C++,我有一个像这样的向量 All_Pos={0,10,15,24,30,33,66} 还有三个更小的向量,它们包含了前一个向量的数字 Vec_Lin={0,15} Vec_Circ={24,33,66} Vec_Arc={10,30} 我想做这样的东西: All_Pos[0]=Vec_Lin[0]? YES -> Do something All_Pos[1]=Vec_Lin[1]?No All_Pos[1]=Vec_Circ[0]?No All_Pos[1]=Vec_Arc[0
All_Pos={0,10,15,24,30,33,66}
还有三个更小的向量,它们包含了前一个向量的数字
Vec_Lin={0,15}
Vec_Circ={24,33,66}
Vec_Arc={10,30}
我想做这样的东西:
All_Pos[0]=Vec_Lin[0]? YES -> Do something
All_Pos[1]=Vec_Lin[1]?No
All_Pos[1]=Vec_Circ[0]?No
All_Pos[1]=Vec_Arc[0]?Yes -> Do Something
等等,直到我完成我的所有步骤。问题是我得到的向量超出了范围,我不知道如何修复它
int counter_linie=0;
int counter_cerc=0;
int counter_arc=0;
for (int p = 0; p < All_pos.size(); p++)
{
if(All_pos[p] == Vec_Lin[counter_linie])
{
//Do something
counter_linie++;
}
if (All_pos[p] == Vec_circ[counter_cerc])
{
//Do something
counter_cerc++;
}
if (All_pos[p] == Vec_Arc[counter_arc])
{
/Do something
counter_arc++;
}
}
int计数器=0;
int计数器=0;
int计数器_弧=0;
对于(int p=0;p
您正在尝试访问较小向量中不存在的元素
Vec\u circ
只能通过索引0、1和2访问,但在您的循环中对Vec\u circ
进行三次成功检查后,counter\u cerc
将为3。
尝试访问Vec\u circ[3]
会导致错误
您需要一种机制来防止这种情况。您应该检查是否超出范围。[]当索引处于从“0”到vector.size()的限制范围内时,运算符起作用
void过程向量(void)
{
向量All_Pos={0,10,15,24,30,33,66};
std::Vec_Lin={0,15};
std::Vec_Circ={24,33,66};
向量向量向量弧={10,30};
int计数器的线性=0;
int计数器=0;
int计数器_弧=0;
对于(int p=0;p std::cout您应该使用调试器逐步检查代码以查看问题
最初的值是:
int counter_linie=0;
int counter_cerc=0;
int counter_arc=0;
counter_linie=1;
counter_cerc=0;
counter_arc=0;
counter_linie=1;
counter_cerc=0;
counter_arc=1;
counter_linie=2;
counter_cerc=0;
counter_arc=1;
第一次迭代后,值为:
int counter_linie=0;
int counter_cerc=0;
int counter_arc=0;
counter_linie=1;
counter_cerc=0;
counter_arc=0;
counter_linie=1;
counter_cerc=0;
counter_arc=1;
counter_linie=2;
counter_cerc=0;
counter_arc=1;
第二次迭代后,值为:
int counter_linie=0;
int counter_cerc=0;
int counter_arc=0;
counter_linie=1;
counter_cerc=0;
counter_arc=0;
counter_linie=1;
counter_cerc=0;
counter_arc=1;
counter_linie=2;
counter_cerc=0;
counter_arc=1;
第三次迭代后,值为:
int counter_linie=0;
int counter_cerc=0;
int counter_arc=0;
counter_linie=1;
counter_cerc=0;
counter_arc=0;
counter_linie=1;
counter_cerc=0;
counter_arc=1;
counter_linie=2;
counter_cerc=0;
counter_arc=1;
现在你试着去阅读
Vec_Lin[2]
在
这就是你的问题。在if条件中添加一个检查
if(counter_linie < Vec_Lin.size() && All_pos[p] == Vec_Lin[counter_linie])
if(counter_line
请提供一份详细的信息。