C++ Vector size is returning zero

12,819

Solution 1

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.

Solution 2

reserve just pre-allocates memory, it does not change size. You could omit reverse and just use

vector<int> v1(30);

Alternatively, and perhaps better, you can utilize push_back:

vector<int> v1;
v1.push_back(1);
for (int index = 1; index < 30; index++)
{
    v1.push_back(v1[v1.size()-1] + (rand()%10));
}

Solution 3

v1.reserve(30);

does not change the number of elements in the vector, it just makes sure the vector has enough space to save 30 elements without reallocation. Use

v1.resize(30);

to change to number of elements in the vector or use

std::vector<int> v1(30);

to initialize the v1 to contain 30 ints initialized to 0.

Also have a look at the documentation to read up on what the std::vector member functions do exactly.

Share:
12,819
NB2345
Author by

NB2345

Updated on June 04, 2022

Comments

  • NB2345
    NB2345 almost 2 years

    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;
        }