我如何在 C++ 中将整数 vector 转换为单个整数?
vector<int>myints = {3, 55, 2, 7, 8}
预期答案:355278
最佳答案
这是一种快速而肮脏的方法:
using namespace std;
vector<int> myints = {3, 55, 2, 7, 8};
stringstream stream;
for(const auto &i : myints)
{
stream << i;
}
int value = stoi(stream.str());
这里有一种不用字符串的方法:
using namespace std;
vector<int> myints = {3, 55, 2, 7, 8};
int value = 0;
for(auto i : myints)
{
int number = i;
do
{
value *= 10;
i /= 10;
}while(i != 0);
value += number;
}
cout << value << endl;
i/= 10
是这里的关键位,因为它根据当前数字 i
关于c++ - 如何在 C++ 中将 vector<int> 连接到单个 int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46430727/