I have such a method
void foo(std::vector<std::array<int, 3>> iVec){
....
}
I don't want to change this method, but I need to pass as param this vector std::vector<int>
As far as I understand this two vectors are taking the same memory... So, theoretical I can use method std::move
to move this vector as is. But this vectors has a different size.. so... I don't know...
One guy told me that it could be possible if change the function that it will get two int pointers, and so it could be possible.
But I don't understand what does it mean without a example... If someone could provide an example I really appreciate.
But anyway question still is: if is it possible to pass my vector as a function param that has another type. If yes, so how?
Fell free to ask
The C++ standard does not guarantee that sizeof(std::array<MyType, N>)==sizeof(MyType)*N
. That is, even though the elements of an individual std::array
are contiguous, a vector
of array
s may not have the elements of the arrays evenly spaced. So there is no standard-compliant way of doing this, because the two vectors would not necessarily be "taking the same memory".
You could maybe get things to work with reinterpret_cast
and such on your compiler. ( std::move
from a reinterpreted vector type will definitely not work, not in theory and not in practice.) This will not be portable or reliable or a good idea. You have three options: copy the data, change the source type, or change the destination type.
I don't want to change this method ...
But you should. If you make it work with iterators rather than the container, you will get more flexibility:
template <typename IT>
void foo(IT begin, IT end){
....
}
Now passing begin
and end
of whatever container is possible. However, if you want to go back to passing iterators to a std::vector<std::array<int, 3>>
you would have to invest some extra effort to get an iterator type that lets you iterate from [0][0]
till [size_x][size_y]
, but as the arrays all have size 3, this shouldnt be too complicated. And anyhow you should consider to use flat vectors instead of a 2D structure.
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.