aj_
aj_

Reputation: 19

Why do I see size of vector as zero?

void pre_process(string& pattern, vector<int>& c)
{
    c.reserve(pattern.length());
    c[0] = -1;
    c[1] = 0;
    for(int i=2; i<pattern.length(); ++i)
    {
        if(pattern[c[i-1]] == pattern[i-1])
            c[i] = c[i-1]+1;
        else
            c[i] = 0;
    }
    cout << c.size() << endl; //why the size is zero here?

}

After reserving the space in vector, I am assigning values to different positions of vector. So shouldn't the size be increased?

What is the right way to use vector as a fixed length container?

Upvotes: 0

Views: 233

Answers (1)

juanchopanza
juanchopanza

Reputation: 227390

Because std::vector::reserve doesn't resize a vector. It simply re-allocates a larger chunk of memory for the vector's data (and copies elements from the original if necessary).

You need std::vector::resize for that:

c.resize(pattern.length());

Currently, you are accessing c out of bounds.

Alternatively, you can keep the call to resize and use push_back instead of operator[]

c.reserve(pattern.length());
c.push_back(-1);
c.push_back(0);

Upvotes: 6

Related Questions