The size() for vectors in C++ standard library returns zero The size() is supposed to return the current number of elements.
Is something wrong with my code ? Or is it a bug in the function ? It happens on MinGW compiler on my PC and also g++ compiler on Linux VW
The capacity() returns the expected result.
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;
}
Add new elements using v1.push_back(...)
. At the moment, you're simply reserving memory in the vector
- which does not change the size, only its capacity.
Manipulating the vector
with the index operator afterwards is bad style, you should only retrieve/edit elements which are already defined as "in the container". In contrast to other languages the index operator does not automatically add elements to your container. In your case you're simply manipulating some reserved memory. Note: the "checked" access method at()
would throw an exception in your case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With