C ++:如何将字符串对象复制到int数组? [英] C++: How to copy a string object to an int array?
问题描述
我在C ++中有一串数字:like string str =1234567012
I have a string of numbers in C++: like string str="1234567012"
-
int阵列,使得阵列的每个元素将具有一个数字。现在我可以使用迭代器,并一次迭代一个,并使用
static_cast< int>(* 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 :: transform
函数:
std::vector<int> ints(str.size());
std::transform(str.begin(), str.end(), ints.begin(),
[](char c) { return c - '0'; });
如果你的编译器不支持lambdas,你可以使用一个普通函数:
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屋!