【问题标题】:Using lower_bound function in loop is giving runtime error?在循环中使用 lower_bound 函数会产生运行时错误?
【发布时间】:2017-05-15 10:19:55
【问题描述】:

以下代码导致运行时错误。在给定代码中,'blocked' 和 'passed' 是两个字符串向量,长度分别为 bl 和 pl。 'low' 是字符串向量的迭代器。

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。请帮忙!

【问题讨论】:

  • 一般来说你应该检查你从算法中得到的迭代器是否等于passed.end(),因为你不能取消对结束迭代器的引用。在这种情况下,您的 index 可能已关闭

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


【解决方案1】:

在第 57 行的第二次循环迭代中,数组的索引 = 2:

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

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

【讨论】:

  • 感谢信息!..这是我第一次使用这个 stl
  • 但我想知道......我会写什么语句来避免下界()将迭代器返回到末尾
  • @lazarus 你无法避免它,但你可以检查它是否确实返回 end:if (low == pased.end()) { /* handle this case*/} else { /* use low */}
猜你喜欢
  • 2019-10-24
  • 2018-12-09
  • 2020-04-14
  • 1970-01-01
  • 2016-08-09
  • 1970-01-01
  • 2021-04-26
  • 2021-01-14
相关资源
最近更新 更多