错误总结反思
0.概述
这篇文章旨在记录我真实经历过的一些值得反思的错误,可能是自己犯的错误,也可能是其他人犯的错误。但是都是一些值得反思的问题,文章结构可能会比较乱,以后记录的问题多了肯定会再进行梳理。
1.vector size为0
在做"求TopK"算法问题时,遇到结果错误问题。经过调试发现那个长度为K的大顶堆vector
int findKthSmallest(vector<int>& nums, int k)
{
vector<int>heapVec;
int res=0;
if(k<=0 || nums.size()<=0)
return -1;
heapVec.reserve(k+1);
for(int i=0;i<k;++i)
{
heapVec[i+1]=nums[i]; //低级错误
}
cout<<"heapVec size="<<heapVec.size()<<endl;//heapVec size=0;
//后续操作......
return res;
}
int main()
{
vector<int>testVec={1,2,3,4};
findKthSmallest(testVec,2);
}
异常情况是heapVec.size()返回0.
原因分析:
heapVec.reserve(k+1);//只改变了heapVec的容量,capacity()返回k+1.但是不改变heapVec的size,size还是0。
heapVec[i+1]=nums[i];//其实经过reserve后,已经申请了内存。但是heapVec的size为0,执行后还是为0.
解决方法:
改用push_back,既然用了STL就尽量不要像C语言一样用下标访问元素。
heapVec.push_back(nums[i]);
深入分析:
如果对一个空vector的元素赋值,运行直接段错误
vector<int>testVec;
testVec[0]=1;//segmentation fault (core dumped)
源码分析(待补充):
2.迭代器erase和string find
错误使用C++ STL中string的find函数。
string str="HELL";
if(false == str.find('E'))
cout<<"NO"<<endl;
else
cout<<"YES"<<endl;
find原型为:
size_type find( CharT ch, size_type pos = 0 ) const;
Return value:
Position of the first character of the found substring or npos if no such substring is found.
static const size_type npos = -1;
返回的是位置信息,不是bool结果。
所以正确用法:
string str="HELL";
if(str.npos == str.find('E'))
cout<<"NO"<<endl;
else
cout<<"YES"<<endl;
经验教训:
不确定的STL语法,不要根据自己平时的开发习惯想当然认为,要去查清楚。
在循环中错误使用erase删除元素
map<string,int>mapSI;
mapSI.insert(make_pair("ab",1));
mapSI.insert(make_pair("cd",2));
mapSI.insert(make_pair("ef",3));
auto it = mapSI.begin();
while(it!=mapSI.end())
{
if(it->first=="ab")
mapSI.erase(it);
it++;
}
erase通过迭代器删除元素后,返回下一个元素的迭代器,原迭代器已经失效。
正确用法:
map<string,int>mapSI;
mapSI.insert(make_pair("ab",1));
mapSI.insert(make_pair("cd",2));
mapSI.insert(make_pair("ef",3));
auto it = mapSI.begin();
while(it!=mapSI.end())
{
if(it->first=="ab")
it = mapSI.erase(it);
else
it++;
}

浙公网安备 33010602011771号