多个查询的循环过早终止

Loop terminating prematurely for multiple queries

本文关键字:终止 循环 查询      更新时间:2023-10-16

对于这个问题,我需要执行多个查询,所以我为它使用了 for 循环

#include<bits/stdc++.h>
using namespace std;
int main(){
vector<int>ans; //vector to store the ans
string s,e; //real dna and virus dna 
cin>>s;
int q,start,match=0; // no. of queries, starting value of the query, var to store matching occurence
unsigned int step=0; //var to keep count of virus dna iteration
cin>>q;
for(int i=0;i<q;i++){//loop to iterate q times 
cin>>start;
int l,r,x,c; 
if(start==2){ // for 2nd type query
cin>>l>>r>>e;
for(int i=l-1;i<=r-1;i++){
if(s[i]==e[step]){
match+=1;   
}
step+=1;
if(step== e.length()){
step=0;        //starting again from start of virus
}
}   
}
ans.push_back(match);
match=0;   //reintializing value for next query

if(start==1){ //for 1st type query
cin>>x>>c;
s[x-1]=c; //replacing char at x-1 with c
}

}

for(int j=0;j<ans.size();j++){ //loop for ans output
cout<<ans[j]<<endl;
}
return 0;
}

但它在应该之前终止,例如:对于此输入,

ATGCATGC
4  
2 1 8 ATGC  
2 2 6 TTT  
1 4 T 
2 2 6 TA

它将在第 5 行停止并打印 8,2,0, 0,而它应该是 8、2、4。如果我在没有循环的情况下进行单个查询,事情可以正常工作,但任何类型的循环都不起作用。请帮忙。此外,任何更有效地解决此类问题的建议都将对我非常有帮助。

代码中更大的问题是变量c被定义为int

int l,r,x,c;

当接收字符而不是整数(在您的示例中为T(时,应定义为char

int l,r,x; 
char c; 

如果cint,当您将4 T发送到

cin>>x>>c;

x接收 4,c没有收到T(T不是有效的int(,因此开始外部循环的下一次迭代,称为

cin>>start;

T留在缓冲区中时;start是整数,所以有同样的问题,程序结束。

而且,正如很快指出的那样,ans.push_back()应该在第一个如果之内。现在,还添加了一个值(零(,并以1开头的行。