转换向量<int>到整数 [英] Convert vector&lt;int&gt; to integer

查看:35
本文介绍了转换向量<int>到整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找用于将整数向量转换为普通整数的预定义函数,但我没有找到.

I was looking for pre-defined function for converting a vector of integers into a normal integer but i din't find one.

vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);

需要这个:

int i=123 //directly converted from vector to int

有没有可能实现这一目标的方法?

Is there a possible way to achieve this?

推荐答案

使用 C++ 11:

reverse(v.begin(), v.end());
int decimal = 1;
int total = 0;
for (auto& it : v)
{
    total += it * decimal;
    decimal *= 10;
}

现在应该是正确的方式.

Now it should be the right way.

编辑 2:请参阅 DAle 的答案以获得更短/更简单的答案.

EDIT 2: See DAle's answer for a shorter/simpler one.

为了将其包装成一个函数以使其可重用.谢谢@Samer

For the sake of wrapping it into a function to make it re-usable. Thanks @Samer

int VectorToInt(vector<int> v)
{
    reverse(v.begin(), v.end());
    int decimal = 1;
    int total = 0;
    for (auto& it : v)
    {
        total += it * decimal;
        decimal *= 10;
    }
    return total;
}

这篇关于转换向量<int>到整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆