[英]What is the correct way to convert an int array to string?
我在想最好的方法是转换一个整数数组,例如
int array[] = {0x53,0x74,0x61,0x63,0x6B,0x4F,0x76,0x65,0x72,0x66,0x6C,0x6F,0x77,0x00}
字符串,上面的整数数组等效于:
int array[] = {'S','t','a','c','k','O','v','e','r','f','l','o','w',0}
所以结果字符串将是
std::string so("StackOverflow");
我当时想用foreach遍历eacht元素,然后将其转换为char
并将其添加到字符串中,但是我想知道是否存在更干净/更快/更整洁的方法?
一个int
可隐式转换为char
,您不需要任何强制转换。 所有标准容器的构造函数都带有一对迭代器,因此您可以传递数组的开始和结束:
std::string so( std::begin(array), std::end(array) );
这可能不会比手动循环更快,但是我认为它符合更整洁的标准。
还有一种干净的方法可以对指针数组进行相同操作。 使用Boost间接迭代器:
#include <boost/iterator/indirect_iterator.hpp>
std::string s (
boost::make_indirect_iterator(std::begin(array)),
boost::make_indirect_iterator(std::end(array)) );
我刚注意到的另一件事-您不需要在int数组中仅将0标记为字符串的结尾。 std::end
将推断出数组的大小,而0最终会出现在结果字符串中。
如果您正在寻找(稍微)更快的方法,则可以执行以下操作:
char str[sizeof(array)/sizeof(*array)];
for (int i=0; i<sizeof(array)/sizeof(*array); i++)
str[i] = (char)array[i];
std::string so(str);
这将“保存”重复调用std::string::operator+=
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.