Home > Article > Backend Development > 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!