c++ vector is empty, size()-1 pit

The size() function of vector returns an unsigned integer. When size() == 0, subtracting 1 again will cause overflow, which will make the data larger.
As the code:

int main()
{
    
    
	vector<int> arr;
	cout<<arr.size()<<endl;		// 输出  0
	cout<<arr.size() - 1<<endl;	// 输出  429496729
}

The solution is as follows:

int main()
{
    
    
	vector<int> arr;
	cout<<arr.size()<<endl;// 输出  0
	int a = arr.size() - 1;	// 赋值给有符号整数
	cout<< a <<endl;	// 输出  -1
	
	// /如果是做大小判断的话
	int index = - 1;
	if(index + 1 < arr.size()){
    
    	//把 - 1 移到另一端即可
		arr[++index] = 1;
	}else{
    
    
		++index;
		arr.emplace_back(1);
	}
}

Guess you like

Origin blog.csdn.net/h799710/article/details/109445906