"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How do you convert a vector of integers to a delimited string in C++?

How do you convert a vector of integers to a delimited string in C++?

Published on 2024-11-08
Browse:922

How do you convert a vector of integers to a delimited string in C  ?

Join Vector of Integers into a Delimited String

In C , converting a vector of integers into a string delimited by a specific character can be achieved through various approaches.

Using a Stringstream

One method involves using a std::stringstream, as shown in the following code:

#include 
//...

std::stringstream ss;
for (size_t i = 0; i 

Here, the stringstream object ss is used to sequentially append the integers to the string while inserting a comma as the delimiter.

Utilizing std::for_each

Alternatively, you can use the std::for_each algorithm along with a custom lambda function:

#include 
#include 
//...

std::stringstream ss;
std::for_each(v.begin(), v.end(), [&ss](int i) {
  if (ss.str().size() != 0)
    ss 

In this approach, the lambda function inserts a comma when iterating over subsequent elements, ensuring the correct delimiter placement.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3