将矢量分解为这些数字的整数

时间:2018-05-24 05:45:53

标签: c++ vector int

有没有办法做到这一点?基本上我试图将int的数字放入向量中,而不是相反。这样如果vectorrandom值是5,6,7 ......我可以转换为值为" 567"的int。这甚至是可行的还是可行的?

2 个答案:

答案 0 :(得分:1)

以下函数可用于将整数向量转换为单个整数。

std::string Join(const std::vector<int>& intVector)
{
    std::stringstream ss;
    for (const auto& element : intVector)
    {
        ss << element;      
    }
    return ss.str();
}

在上面的实现中,使用基于范围的for循环,因为c ++ 11中提供了此功能。您可以使用normal for循环。 要将返回的字符串值转换为整数,可以使用std :: stoi算法(c ++ 11)或atoi函数。

答案 1 :(得分:0)

int Join(const std::vector<int>& intVector)
{
    unsigned long sum = 0;
    for (const int& i : intVector)
    {
        sum = (sum << 3) + (sum << 1); // sum*8 + sum*2 = sum*10;
        sum += i;
    }
    return sum;
}
相关问题