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?
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()));
vector<vector<double>> b;
b.reserve(a.size());
for (const auto& elem : a) {
b.emplace_back(elem.begin(), elem.end());
}
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.