我正在开发一个试图使用stringstream的程序,并且对流在幕后的实际工作方式感到困惑。
请考虑以下示例:
char * dataset = new char[3000];
stringstream buff;
for (unsigned int i = 0; i < 3000; ++i)
if (dataset[i] != 32)
buff.put(dataset[i]);
delete[] dataset;
string temp = buff.str();
另一种方法是:
char * dataset = new char[3000];
//Count the number of spaces
unsigned int unwanted = 0;
for (unsigned int i = 0; i < 3000; ++i)
if (dataset[i] == 32)
++unwanted;
//Copy all characters other than spaces
char * temp = new char[3000 - unwanted];
for (unsigned int i = 0, j = 0; i < 3000 - unwanted; ++j)
if (dataset[j] != 32)
temp[i++] = dataset[j];
delete[] dataset;
dataset = temp;
现在这里的困惑是:
流如何继续接受字符而不关心大小?我的意思是我只是继续放置一个字符,然后继续添加到流缓冲区中。我的直觉还告诉我,如果流达到大小限制,它们可能会扩展,因此它们可能不维护字符串或类似的数据结构。
那么究竟是什么驱动了这些流?我的意思是在这些流下使用哪种数据结构。而且我们甚至有一个流大小限制吗?还是可以继续添加而不必担心超出大小?
最后,从以上两种方法中,哪一种更好。我尝试对一个147K字符数组进行分析,而第二个似乎更好地工作。