c++ - 在 C++ 中不使用显式 for 循环将 int [] 转换为字符串

标签 c++ arrays string

我需要将 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/

相关文章:

c++ - 将 %s 格式说明符与 boost::format 和 std::string 一起使用

c++ - 在 va_list 对象中包含第一个参数

python - 如何将字符串转换为时间戳进行比较?

javascript - 修改动态嵌套数组,只知道要访问的索引

java - 销售点 - 卡在阵列上

java - StringUtils.isNumeric() 方法规范在逻辑上是否正确?

c - 忽略字符串中的逗号

c++ - 上交所注册管理

c++ - 使用 dlopen() 引用共享库插件的正确方法是什么?

c# - 无法反序列化当前的 JSON 数组(例如 [1,2,3])