Home » C++ » C++ convert vector<int> to vector<double>

C++ convert vector<int> to vector<double>

Posted by: admin November 30, 2017 Leave a comment

Questions:

What is a good clean way to convert a std::vector<int> intVec to std::vector<double> doubleVec. Or, more generally, to convert two vectors of convertible types?

Answers:

Use std::vector‘s range constructor:

std::vector<int> intVec;
std::vector<double> doubleVec(intVec.begin(), intVec.end());

Questions:
Answers:

Any problem? I can run on my PC. My IDE is Code::blocks.

#include <iostream>
#include <vector>
#include <iterator>
using namespace std;

int main()
{
    vector<int> v_int;
    for (int i=0; i<10; ++i) {
        v_int.push_back(i);
    }
    vector<double> v_float(v_int.begin(), v_int.end());

    copy (v_float.begin(), v_float.end(), ostream_iterator<double>(cout, " "));
    cout << endl;
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *