本文介绍了std :: strings的capacity(),reserve()& resize()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要使用std :: string简单地创建一个动态缓冲区,并使用索引迭代它。是resize()实际分配缓冲区的唯一函数吗?



我尝试了reserve(),但是当我尝试通过索引访问字符串它断言。当字符串的默认容量似乎是15字节(在我的情况下),但如果我仍然不能访问它 my_string [1]



所以字符串的容量不是实际的缓冲区?此外,reserve()也不会分配实际的缓冲区?

  string my_string; 

//我想我的字符串有20个字节长的缓冲区
my_string.reserve(20);

int i = 0;

for(parsing_something_else_loop)
{
char ch =< business_logic> ;;

//将字符存储在
中my_string [i ++] = ch; //这崩溃
}

如果我做resize它工作正常。这是什么字符串有能力,但不能真正访问它与[]?

附加组件
为了响应答案,我想问问stl人,为什么任何人使用reserve()当resize()做完全一样,它也初始化字符串?我不得不说我不喜欢这种情况下的性能论据太多。所有的resize()做额外的reserve()做的是,它只是初始化缓冲区,我们知道是总是很好做的反正。我们可以从岛上投票预订()吗?

解决方案

不,这是 resize c $ c>。



reserve()只给予足够的空间,大小(例如调用 push_back())将更有效。



从您的使用案例看,您应该使用 .push_back()

  my_string.reserve(20); 

for(parsing_something_else_loop)
{
char ch =< business_logic> ;;
my_string.push_back(ch);
}






调用<$ c $> c> .reserve()就像吹起山,给你一些自由土地。自由土地的数量是 .capacity()。土地在那里,但这并不意味着你可以住在那里。你必须建造房子才能搬进来。房屋数量是 .size()(= .length())。



假设你正在建造一座城市,但在建造50之后,你发现没有足够的土地,所以你需要找到另一个足够大的地方以适应第51所房子,然后将整个人口迁移到那里。这是非常低效的。如果你知道你需要建立1000个房子的前面,那么你可以调用

  my_string.reserve(1000); 

以获得足够的土地建造1000栋房屋,然后拨打

  my_string.push_back(ch); 

使用 ch 到此位置。您可能不会说

  my_string [16] ='c'; 

因为房子#16不存在。您可以致电

  my_string.resize(20); 

一次性建立#0〜#19房屋,这就是为什么

  my_string [i ++] = ch; 

工作正常(只要0≤ i ≤19) / p>

另请参阅。






对于您的附加问题,
$ b

.resize()无法完全替换 .reserve() )你不总是需要使用所有分配的空间,和(2)默认构造+副本分配是一个两个步骤的过程,这可能需要更多的时间比直接构建(尤其是大对象),即

  #include< vector> 
#include< unistd.h>

struct SlowObject
{
SlowObject(){sleep(1); }
SlowObject(const SlowObject& other){sleep(1); }
SlowObject& operator =(const SlowObject& other){sleep(1); return * this; }
};

int main()
{
std :: vector< SlowObject> my_vector;

my_vector.resize(3);
for(int i = 0; i my_vector [i] = SlowObject();

return 0;
}

会浪费至少9秒钟运行,而

  int main()
{
std :: vector< SlowObject> my_vector;

my_vector.reserve(3);
for(int i = 0; i my_vector.push_back(SlowObject());

return 0;
}

只浪费了6秒钟。



std :: string 仅复制 std :: vector 的界面。


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?

I tried reserve() but when I try to access the string via index it asserts. Also when the string's default capacity seems to be 15 bytes (in my case) but if I still can't access it as my_string[1].

So the capacity of the string is not the actual buffer? Also reserve() also does't allocate the actual buffer?

string my_string;

// I want my string to have 20 bytes long buffer
my_string.reserve( 20 );

int i = 0;

for ( parsing_something_else_loop )
{
    char ch = <business_logic>;

    // store the character in 
    my_string[i++] = ch; // this crashes
}

If I do resize() instead of reserve() than it works fine. How is it that the string has the capacity but can't really access it with []? Isn't that the point to reserve() size so you can access it?

Add-onIn response to the answers, I would like to ask stl folks, Why would anybody use reserve() when resize() does exactly the same and it also initialize the string? I have to say I don't appreciate the performance argument in this case that much. All that resize() does additional to what reserve() does is that it merely initialize the buffer which we know is always nice to do anyways. Can we vote reserve() off the island?

解决方案

No, that's the point of resize().

reserve() only gives to enough room so that future call that leads to increase of the size (e.g. calling push_back()) will be more efficient.

From your use case it looks like you should use .push_back() instead.

my_string.reserve( 20 );

for ( parsing_something_else_loop )
{
    char ch = <business_logic>;
    my_string.push_back(ch);
}


Calling .reserve() is like blowing up mountains to give you some free land. The amount of free land is the .capacity(). The land is there but that doesn't mean you can live there. You have to build houses in order to move in. The number of houses is the .size() (= .length()).

Suppose you are building a city, but after building the 50th you found that there is not enough land, so you need to found another place large enough to fit the 51st house, and then migrate the whole population there. This is extremely inefficient. If you knew you need to build 1000 houses up-front, then you can call

my_string.reserve(1000);

to get enough land to build 1000 houses, and then you call

my_string.push_back(ch);

to construct the house with the assignment of ch to this location. The capacity is 1000, but the size is still 1. You may not say

my_string[16] = 'c';

because the house #16 does not exist yet. You may call

my_string.resize(20);

to get houses #0 ~ #19 built in one go, which is why

my_string[i++] = ch;

works fine (as long as 0 ≤ i ≤ 19).

See also http://en.wikipedia.org/wiki/Dynamic_array.


For your add-on question,

.resize() cannot completely replace .reserve(), because (1) you don't always need to use up all allocated spaces, and (2) default construction + copy assignment is a two-step process, which could take more time than constructing directly (esp. for large objects), i.e.

#include <vector>
#include <unistd.h>

struct SlowObject
{
    SlowObject() { sleep(1); }
    SlowObject(const SlowObject& other) { sleep(1); }
    SlowObject& operator=(const SlowObject& other) { sleep(1); return *this; }
};

int main()
{
    std::vector<SlowObject> my_vector;

    my_vector.resize(3);
    for (int i = 0; i < 3; ++ i)
        my_vector[i] = SlowObject();

    return 0;
}

Will waste you at least 9 seconds to run, while

int main()
{
    std::vector<SlowObject> my_vector;

    my_vector.reserve(3);
    for (int i = 0; i < 3; ++ i)
        my_vector.push_back(SlowObject());

    return 0;
}

wastes only 6 seconds.

std::string only copies std::vector's interface here.

这篇关于std :: strings的capacity(),reserve()&amp; resize()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 08:04