Reputation: 11
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?
Upvotes: 1
Views: 4818
Reputation: 3082
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()
Upvotes: 0
Reputation: 52621
vector<vector<double>> b;
b.reserve(a.size());
for (const auto& elem : a) {
b.emplace_back(elem.begin(), elem.end());
}
Upvotes: 1
Reputation: 56577
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()));
Upvotes: 3