1

I know the cast from the first array.

std::vector<int> v_int;
std::vector<float> v_float(v_int.begin(), v_int.end());

but how do I convert second array?

vector<int> aCol(4);
vector<vector<int>> a(2, aCol);
vector<vector<double>> b(a.begin(), a.end());// ???

What should I do in this case?

Alejandro
  • 3,040
  • 1
  • 21
  • 30
윤희동
  • 11
  • 1
  • 4
  • 1
    To copy the contents of a `std::vector` to a`std::vector`? – Alejandro Jun 25 '15 at 03:40
  • 1
    You want `std::vector v_int(v_float.begin(), v_float.end());`? What problem did you encounter? – songyuanyao Jun 25 '15 at 03:42
  • vector aCol(4); vector< vector > a(2, aCol); vector< vector > b(a.begin(), a.end()); ?????????????? – 윤희동 Jun 25 '15 at 03:43
  • 2
    @윤희동, I still have no idea what you're asking. What do you want to "convert"? – Alejandro Jun 25 '15 at 03:44
  • http://stackoverflow.com/questions/6399090/c-convert-vectorint-to-vectordouble I think is just a repeat of this question. – Matt Jun 25 '15 at 03:48
  • @윤희동, For your edited question ( which had nothing to do with the original), you're trying to construct a `vector>` with a range of `vector>`s. There's no conversion from `vector` to `vector`. What did you expect would happen? You may want to look at `std::copy` instead. – Alejandro Jun 25 '15 at 03:49
  • I'm expect type casting.. int -> double but x1, x2, x3, x4,... one array ok, x1 y1, x1 y2, x1, y3, x1 y4 two array not ok.. i want to know two array convert – 윤희동 Jun 25 '15 at 03:54
  • Thack you for reading^^ – 윤희동 Jun 25 '15 at 03:55

3 Answers3

3

For the compiler vector<int> and vector<double> are completely unrelated types, not implicitly convertible one to another. What you can do is something like:

for(auto&& elem: a)
    b.push_back(std::vector<double>(elem.begin(), elem.end()));
vsoftco
  • 55,410
  • 12
  • 139
  • 252
1
vector<vector<double>> b;
b.reserve(a.size());
for (const auto& elem : a) {
  b.emplace_back(elem.begin(), elem.end());
}
Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
0

The reason your vector-of-vectors construction is not compiling is because

vector<vector<double>> b(a.begin(), a.end())

is range constructing b with iterators whose element type is vector<int>. This will attempt to construct b's internal std::vector<double>s with std::vector<int>s, which is no surprise that it shouldn't compile.

Comparing this to your first example,

std::vector<float> v_float(v_int.begin(), v_int.end());

is range constructing v_float from iterators whose element type is int. This works because a conversion from an int to a float is allowed, but not from std::vector<int> to std::vector<double> (or std::vector<float>).

You may want to instead look at looping through each element of a and pushing back a vector constructed from a's begin() and end()

Alejandro
  • 3,040
  • 1
  • 21
  • 30