为什么代码给出分段错误?



我正在解决hackerrank中的攀爬排行榜问题,但我的函数给出了分段错误。

vector<int> climbingLeaderboard(vector<int> scores, vector<int> alice) {
vector<int> res,i;
auto ip=  unique(scores.begin(),scores.begin()+scores.size());
scores.resize(distance(scores.begin(),ip));
for(int i =0;i<alice.size();++i)
{
int curr =0;
while(alice[i]<=scores[curr]&&curr<scores.size())
++curr;

if(alice[i]==scores[curr-1])
res[i]=curr-1;
else if(alice[i]>scores[curr])
res[i]=curr;
else if(curr>scores.size()-1)
res[i]=curr; 



}


return res;

}

它给出以下错误:

> Program terminated with signal SIGSEGV, Segmentation fault.
> #0  0x0000000000402a01 in climbingLeaderboard (scores=..., alice=...)
>     at /usr/local/include/c++/8.3.0/bits/stl_vector.h:930 930       operator[](size_type __n) _GLIBCXX_NOEXCEPT

首先,在不分配任何元素的情况下访问res[i]res.

vector<int> res应该是vector<int> res(alice.size()).

其次,在检查是否curr<scores.size()之前可以访问scores[curr]

while(alice[i]<=scores[curr]&&curr<scores.size())
++curr;

应该是

while(curr<scores.size()&&alice[i]<=scores[curr])
++curr;

else if(alice[i]>scores[curr])
res[i]=curr;
else if(curr>scores.size()-1)
res[i]=curr; 

应该是

else if(curr>scores.size()-1)
res[i]=curr; 
else if(alice[i]>scores[curr])
res[i]=curr;

相关内容

  • 没有找到相关文章