简体   繁体   English

为什么std :: to_string不支持容器类作为输入?

[英]Why doesn't std::to_string support container classes as input?

So std::to_string works on various primitive types. 因此std :: to_string适用于各种原始类型。 However, when trying to print the elements of a container like a vector, I have to iterate through the vector element by element and print each individually. 但是,当尝试像矢量一样打印容器的元素时,我必须逐个元素遍历vector并分别打印。 Now granted, with something like a vector this can amount to a single statement or loop like such: 现在被授予,使用诸如矢量之类的东西,就等于一个语句或循环,如下所示:

for_each(v.begin(), v.end(), [](int x) {cout << x <<", "; });

but with other container classes it can be quite a nuisance to format the data type. 但是对于其他容器类,格式化数据类型可能会很麻烦。

In contrast, languages like Java or Python have functions that print most containers in a single statement. 相反,诸如Java或Python之类的语言具有可在单个语句中打印大多数容器的函数。 Why doesn't STL accept these as arguments in std::to_string or implement to_string as member function of the container classes? 为什么STL不接受这些作为std :: to_string中的参数,或者不实现to_string作为容器类的成员函数?

Vector doesn't know how to convert custom class to string, unless custom classes provide string conversion. Vector不知道如何将自定义类转换为字符串,除非自定义类提供字符串转换。 Now custom classes are not required to provide string conversion because it might be meaning less for that class. 现在,不需要自定义类来提供字符串转换,因为这对于该类来说可能意味着更少的意义。

Containers are very generic in that sense. 从这个意义上说,容器是非常通用的。 And like you pointed, its very easy to implement. 就像您指出的那样,它非常容易实现。 Very typical way is to overload << operator as follows: 非常典型的方法是如下重载<<运算符:

ostream& operator<<(ostream& cout, const vector<int>& sorted)
{
  cout << "Array => ";
  for( auto i : sorted ) {
    cout << i << ", ";
  }
  cout << endl;
  return cout;
}

Or use stringstream class or use for_each ... 或使用stringstream类或使用for_each ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM