gpt4 book ai didi

c++ - 如何在 C++ 中将 vector 连接到单个 int?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:21:11 26 4
gpt4 key购买 nike

我如何在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com