How to convert an integer array to a string array in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <string>

// Converts a vector of integers to a vector of strings.
//
// @param numbers The input integer vector.
// @return A vector containing the string representation of each integer.
std::vector<std::string> convertToStringArray(const std::vector<int>& numbers)
{
    std::vector<std::string> result;
    result.reserve(numbers.size()); // Avoid unnecessary reallocations

    for (int number : numbers) {
        result.push_back(std::to_string(number));
    }

    return result;
}

int main()
{
    std::vector<int> numbers = {10, 20, 30, 40, 50};

    std::vector<std::string> strings = convertToStringArray(numbers);

    // Print the converted strings
    for (const auto& str : strings) {
        std::cout << str << '\n';
    }
}



/*
run:

10
20
30
40
50

*/

 



answered 4 hours ago by avibootz
...