STL(lower_bound)运行时错误
生活随笔
收集整理的這篇文章主要介紹了
STL(lower_bound)运行时错误
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
舉例如下:
一個數組number序列為:4,25,11,48,69,72,96,100.設要插入數字3,9,111.pos為要插入的位置的下標
則
pos = lower_bound( number, number + 8, 3) - number,pos = 0.即number數組的下標為0的位置。
pos = lower_bound( number, number + 8, 9) - number, pos = 1,即number數組的下標為1的位置(即10所在的位置)。
pos = lower_bound( number, number + 8, 111) - number, pos = 8,即number數組的下標為8的位置(但下標上限為7,所以返回最后一個元素的下一個元素)。
所以,要記住:函數lower_bound()在first和last中的前閉后開區間進行二分查找,返回大于或等于val的第一個元素位置。如果所有元素都小于val,則返回last的位置,且last的位置是越界的!!~
返回查找元素的第一個可安插位置,也就是“元素值>=查找值”的第一個元素的位置
?
?
運行時錯誤:可能是數組越界;零作為除數;非法內存讀取;系統棧過載;
解決方法:一般是前兩者,找一下,將數組開大或者看除數;
例題:
A - Where is the Marble?
#include<bits/stdc++.h> using namespace std; int n,q; int N[100000],Q[100000]; ///*方法二 寫一個尋找的函數,略有暴力 int find(int x){int i;for(i=0;i<n;i++){if(N[i]==x){printf("%d found at %d\n",x,i+1);return 1;}}return 0; } //*/ int main(){int i,count=0;while(scanf("%d%d",&n,&q)==2 && n!=0 && q!=0){count++;for(i=0;i<n;i++){scanf("%d",&N[i]);}std::sort(N,N+n);for(i=0;i<q;i++){scanf("%d",&Q[i]);}printf("CASE# %d:\n",count); for(i=0;i<q;i++){int pos=lower_bound(N,N+n,Q[i])-N;/* if(N[pos]==Q[i])方法 printf("%d found at %d\n",Q[i],pos+1);一 else printf("%d not found\n",Q[i]); } 方法一不用寫函數,用 STL,二分查找,很快的; */ if(find(Q[i])==0)printf("%d not found\n",Q[i]);} }return 0;}?
總結
以上是生活随笔為你收集整理的STL(lower_bound)运行时错误的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Vue命名视图
- 下一篇: CVPR2019:Domain-Spec