在循环中使用lower_bound函数会产生运行时错误?

时间:2017-05-15 10:19:55

标签: c++ vector iterator binary-search lower-bound

以下代码导致运行时错误。在给定代码中被阻止'并且通过了#39;是两个字符串向量,分别具有长度bl和pl。 '低'是字符串向量的迭代器。

int pos;
vector<string> f;
vector<string>::iterator low;
for(int i=0;i<bl;i++) {
        string x=blocked[i];
        low=lower_bound(passed.begin(),passed.end(),x); //lower_bound function is used on the vector 'passed'.
        index=low-passed.begin(); //finding the index of the string in the vector 'passed'.
        string y=passed[index];
        int xlen=x.length();
        int ylen=y.length();
        int minlen=min(xlen,ylen);
        for(int i=0;i<minlen;i++) {
            if(x[i]!=y[i]) {
                pos=i;
                break;
              }
            }
            string h=x.substr(0,pos+1);
            f.push_back(h); 
        }
        int d=f.size();
        for(int i=0;i<f.size();i++) {
            cout<<f[i]<<endl;
    }

上述代码的完整代码位于https://ideone.com/4NgCWz。 Plz帮忙!

1 个答案:

答案 0 :(得分:0)

在第57行的循环的第二次迭代中,你得到index = 2的数组:

$5 = std::vector of length 2, capacity 2 = {"codechef", "google"}

您应该检查“lower_bound()”的结果是否等于pass.end()。 如果它相等,则lower_bound()返回迭代器结束,而不是最后一个元素。