我需要将 int[]
转换为字符串。有 std::to_string
方法,但它不将数组作为输入。因此,需要一个 for 循环 like here .有没有什么方法可以在没有显式 for 循环的情况下实现这一点?就像在 Java 中一样,我们可以使用 java.util.Arrays.toString()
来达到这个目的。
编辑:任何可能的解决方法也会有所帮助,以优化的方式解决问题。
最佳答案
这样就可以了
#include <iostream>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <string>
int main()
{
int x[] = {1,2,3,4,5}; // sample array
std::ostringstream os;
std::ostream_iterator<int> out(os, " ");
std::copy(std::begin(x), std::end(x), out);
std::string result = os.str();
}
请记住,result
在最后一个 int
值之后会有一个尾随空格。我将删除它作为练习。
稍微更神秘一些。
std::ostringstream os;
std::copy(std::begin(x), std::end(x), std::ostream_iterator<int>(os, " "));
std::string result = os.str();
在 C++ 中,您不会获得与 Java 完全相同的东西,因为 int []
在 C++ 中比在 Java 中更原始。例如,当作为参数传递给函数时,数组将转换为指向其第一个元素的指针,因此被调用函数不会接收有关元素数量的信息。
关于c++ - 在 C++ 中不使用显式 for 循环将 int [] 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48018187/