Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to use std::generate on an empty std::vector for which we have only called .reserve?

My main function:


#include <vector>
//#include <algorithm>
#include <iostream>

int main()
{

    std::vector<char> v;
    int len = 2 * 5 + 1;
    v.reserve(len);

    // using for loop and push_back

    for (int i = 0; i < len; i++)
        (i % 2) ? v.push_back(' ') : v.push_back('|');

    // using generate

    // std::generate(v.begin(), v.end(), [n = 0]() mutable { return (n++ % 2) ? ' ' : '|'; });
    // std::generate_n(v.begin(), len, [n = 0]() mutable { return (n++ % 2) ? ' ' : '|'; });

    for (const char& c : v)
        std::cout << c;

    return 0;
}

Using for loop and push_back I get the output:

| | | | | |

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Using std::generate has no effect, and using std::generate_n results in a failed assertion:

Expression: cannot seek vector iterator after end

As I understand it, calling .reserve doesn’t change the "distance" between iterators begin and end, so I can’t pass them to std::generate in order to place ‘ ‘ and ‘|’ in the memory I reserved for v. I would have to increase v.end by len (len+1?), is that even possible? Or is there another way to make this work, without using .push_back or similar operations, or without initializing reserved memory with something then overwriting it? Also not sure if the lambda is correct, but that’s not important.

>Solution :

You can use std::generate_n with a std::back_inserter on the container.

This will resize the container as it generates.

The reserve is opional, but it will save on container resizes and reallocations possibly.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading