Home > Backend Development > C++ > body text

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

Susan Sarandon
Release: 2024-11-03 14:22:02
Original
608 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template