Hisham Hijjawi
Hisham Hijjawi

Reputation: 2415

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

So std::to_string works on various primitive types. 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. 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. Why doesn't STL accept these as arguments in std::to_string or implement to_string as member function of the container classes?

Upvotes: 1

Views: 235

Answers (1)

NP Rooski  Z
NP Rooski Z

Reputation: 3657

Vector doesn't know how to convert custom class to string, unless custom classes provide string conversion. 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 ...

Upvotes: 2

Related Questions