C++標準庫中向量的大小()返回零 size()應該返回當前元素數。C++向量大小返回零
我的代碼有問題嗎?或者它是一個函數中的錯誤? 它發生在我的PC上的MinGW編譯器上,也發生在Linux上的g ++編譯器上。容量()返回預期的結果。
using namespace std;
bool binarySearch(vector<int>& nums, int k)
{
int low, high, mid;
low = 0;
high = nums.size();
mid = (low+high)/2;
printf("low %d high %d mid %d \n", low, high, mid);
return true;
}
int main()
{
int result;
vector<int> v1;
v1.reserve(30);
v1[0] = 1;
for (int index = 1; index < 30; index++)
{
v1[index] = v1[index-1] + (rand()%10);
}
bool flag = binarySearch(v1, 57);
return 0;
}
我很困惑,因爲OP的代碼有設置每個索引元素的循環,但是這個頁面是這樣的:http://en.cppreference.com/w/cpp/container/vector/operator_at它說* *運算符[]不會插入新元素**。所以,即使你保留並設置了元素,元素也沒有被插入(沒有任何例外,這不是很有用的信息,你可以像'v1.at(0)= 1'那樣使用'std :: vector :: at'會拋出異常) – texasbruce