std::strings's capacity(), reserve() & resize() functions

后端 未结 6 1487
天命终不由人
天命终不由人 2020-11-27 17:27

I wan to use std::string simply to create a dynamic buffer and than iterate through it using an index. Is resize() the only function to actually allocate the buffer?

6条回答
  •  北海茫月
    2020-11-27 18:14

    No -- the point of reserve is to prevent re-allocation. resize sets the usable size, reserve does not -- it just sets an amount of space that's reserved, but not yet directly usable.

    Here's one example -- we're going to create a 1000-character random string:

    static const int size = 1000;
    std::string x;
    x.reserve(size);
    for (int i=0; i

    reserve is primarily an optimization tool though -- most code that works with reserve should also work (just, possibly, a little more slowly) without calling reserve. The one exception to that is that reserve can ensure that iterators remain valid, when they wouldn't without the call to reserve.

提交回复
热议问题