将vector <int>转换为整数

avi*_*ner 4 c++ stl stdvector

我正在寻找预定义函数将整数向量转换为正常整数,但我找不到.

vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
Run Code Online (Sandbox Code Playgroud)

需要这个:

int i=123 //directly converted from vector to int
Run Code Online (Sandbox Code Playgroud)

有可能实现这个目标吗?

Raf*_*ael 8

使用C++ 11:

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

编辑:现在它应该是正确的方式.

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

为了将其包装成函数以使其可重复使用.谢谢@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;
}
Run Code Online (Sandbox Code Playgroud)

  • 不需要逆转.看到另一个答案. (2认同)

DAl*_*Ale 6

如果向量的元素是数字:

int result = 0;
for (auto d : v)  
{
    result = result * 10 + d;
}
Run Code Online (Sandbox Code Playgroud)

如果不是数字:

stringstream str;
copy(v.begin(), v.end(), ostream_iterator<int>(str, ""));
int res = stoi(str.str());
Run Code Online (Sandbox Code Playgroud)