C++ 使用stringstream还有其他方法吗?

C++ 使用stringstream还有其他方法吗?,c++,C++,我目前正在使用stringstream传递字符串,但我想知道是否有其他方法可以传递?下面是一个如何做的剪贴镜头。由于我对C++仍然很陌生,我不确定这是不是最好的方法,或者我可以用一个替代方案,因为我听说使用String流减缓了进程,希望能学到更多。 string Circle::toString() { stringstream sentence; sentence << "Shape [" << index <<"]" << endl

我目前正在使用
stringstream
传递字符串,但我想知道是否有其他方法可以传递?下面是一个如何做的剪贴镜头。由于我对C++仍然很陌生,我不确定这是不是最好的方法,或者我可以用一个替代方案,因为我听说使用String流减缓了进程,希望能学到更多。
string Circle::toString()
{
   stringstream sentence;
   sentence << "Shape [" << index <<"]" << endl;
   sentence << "Name: " << name << endl;

   if (containsWarpSpace == false)
       sentence << "Special Type: NS" << endl;
   else
       sentence << "Special Type: WS" << endl;

   sentence << "Area: " << area << " units square" << endl;
   sentence << "Vertices: " << endl;
   sentence << "Point[0]: (" << center[0] << ", " << center[1] << ")" << endl;
   sentence << endl;
   sentence << "Points on perimeter: " << endl;
   bool trueFalse= false;
   int count = 0;
   for ( int y = center[1] - unit; y < center[1] + unit + 1; y++)
   {
      for ( int x = center[0] - unit; x < center[0] + unit + 1; x++)
      {
         trueFalse = isPointOnShape (x, y);
         if (trueFalse == true)
         {
            if (count %6 == 0)
                sentence << "(" << x << ", " << y << ")";
            else
                sentence << ", (" << x << ", " << y << ")";

            count++;
            if (count %6 == 0)
                sentence << endl;
         }
      }
   }

   if (count == 0)
       sentence << "none!";

   sentence << endl;
   count = 0;
   sentence << "Points within shape: " << endl;
   for (int y = center[1] - unit; y < center[1] + unit + 1; y++)
   {
      for ( int x = center[0] - unit; x < center[0] + unit + 1; x++)
      {
         trueFalse = isPointInShape (x, y);

         if (trueFalse == true)
         {
            if (count %6 == 0)
                sentence << "(" << x << ", " << y << ")";
            else
                sentence << ", (" << x << ", " << y << ")";

            count++;
            if (count %6 == 0)
                sentence << endl;
         }
      }
   }
   if (count == 0)
       sentence << "none!";

   sentence << endl;    
   return sentence.str();
} 
string循环::toString()
{
串流句;

句子< p>你使用的代码<代码> StrugSuth是很好的,但是你需要考虑你的代码在每个<代码> toSTRIN()中创建一个<代码> StrugSuths<代码>对象。
调用,这反过来会导致内存分配。例如,如果要将一千个圆转储到一个字符串中,那么将有一千个内存分配给临时
stringstream
对象的底层内存缓冲区,最后是一千个释放(如果初始缓冲区不够大,可能会重新分配)


最有可能的情况是,您将使用
toString()
进行调试或日志记录,而性能并不重要。但是,还有改进的余地。请考虑如何处理
Circle::toString()返回的字符串
?最有可能的情况是,字符串将被显示、写入文件或通过网络传输。您将执行类似于
的操作。请尝试提供一个完整的示例,其中包括主要方法,并将代码缩减为与您的问题相关的部分。首先让它工作,然后重试输出性能。作为第一个改进,为points和overload操作符创建一个新类型。如果足够快,我不会担心性能。如果您认为速度太慢,有很多方法可以实现更快的执行,但可能不够优雅。我会先美化您的代码。
trueFalse
不是一个好名字布尔变量。这是对
stringstream
的适当使用。它没有问题。谢谢大家提供的信息