C ++:如何将一个字符串对象复制到一个int数组? [英] C++: How to copy a string object to an int array?
问题描述
我有一个数字在C ++中的字符串:像字符串str =1234567012
I have a string of numbers in C++: like string str="1234567012"
-
我想这个复制到一个int数组,使得阵列中的每个元素都将有一个数字。现在,我可以同时使用迭代器和迭代之一,使用
的static_cast<&诠释GT;(* ITER)
。但有更多的更简单和直接的方法是什么?
I wish to copy this to an int array, such that each element of the array will have one digit. Now I can use an iterator, and iterate one at a time and use
static_cast<int>(*iter)
. But is there any more easier and straightforward method?
最后,我要重新复制的int数组到字符串数组。
finally i want to recopy the int array to a string array.
请帮我上面的2步骤。
推荐答案
您可以使用的std ::变换
功能:
std::vector<int> ints(str.size());
std::transform(str.begin(), str.end(), ints.begin(),
[](char c) { return c - '0'; });
如果你的编译器不支持lambda表达式是,你可以使用常规的功能:
If your compiler doesn't support lambdas yet, you can use a regular function:
int get_digit(char c) { return c - '0'; }
// ...
std::transform(str.begin(), str.end(), ints.begin(), get_digit);
要做好反向操作,你同样可以这样做:
To do the reverse operation, you can do similarly:
std::string s(ints.size(), 0);
std::transform(ints.begin(), ints.end(), s.begin(),
[](int i) { return i + '0'; });
这篇关于C ++:如何将一个字符串对象复制到一个int数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!