简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM