Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Vector size is returning zero [duplicate]

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;
    }
like image 673
NB2345 Avatar asked Dec 25 '22 17:12

NB2345


1 Answers

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.

like image 165
D.R. Avatar answered Jan 12 '23 23:01

D.R.