Home  >  Article  >  Backend Development  >  How to Convert a Vector of Integers to a String in C ?

How to Convert a Vector of Integers to a String in C ?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 14:22:02602browse

How to Convert a Vector of Integers to a String in C  ?

Converting Vector of Integers to String in C

In C , converting a vector of integers to a string involves iterating through the elements and appending them to a string. A straightforward method is to use a stringstream.

<code class="cpp">#include <sstream>

std::stringstream ss;
for (size_t i = 0; i < v.size(); ++i) {
  if (i != 0) {
    ss << ",";
  }
  ss << v[i];
}
std::string result = ss.str();</code>

Alternatively, the std::for_each function allows you to achieve this in a more elegant manner:

<code class="cpp">std::string result;
std::for_each(v.begin(), v.end(), [&](int n) { result += std::to_string(n) + ","; });
result.pop_back(); // Remove the trailing comma</code>

The above is the detailed content of How to Convert a Vector of Integers to a String in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn