2016-12-02 44 views
0

例如如何在一行中移動數組?

using namespace std; 

array<vector<int>, 3> a; 
vector<int> v0, v1, v2; 

// assign with move 
a[0] = move(v0); 
a[1] = move(v1); 
a[2] = move(v2); 

如何用一條線來實現像a = {v0, v1, v2}分配?

+0

你嘗試'一個=陣列,3>({V0,V1, V2})'? –

+0

'a = {v0,v1,v2}'實際上起作用。 – Rakete1111

+0

@ Rakete1111 checked'a = {move(v0),move(v1),move(v2)};'。有用。任何人都可以解釋它? – user1899020

回答

0

如果你想初始化一個新std::arrayarray<vector<int>, 3> a = { move(v0), move(v1), move(v2) }永遠正常運行,否則建立一個臨時std::array然後用std::move<algorithm>

array<unique_ptr<int>, 3> temp_arr = { move(a), move(b), move(c) }; 
move(begin(temp_arr), end(temp_arr), begin(arr)); 
0

@ user1899020:你可以參考這個What is std::move(), and when should it be used?

請注意「移動語義是對程序員透明地執行的,只移動一個轉換以將值從一個點傳遞到另一個點,原始的左值將不再使用。」

所以在下面的代碼:

a= {move(v0), move(v1), move(v2)}; 

for(int i=0; i <3; i++) 
{ 
    // Iterate and print values of vector 
    for(int n : a[i]) { 
     std::cout << n << '\n'; 
    } 
} 

**//Code will NOT enter below for loop** 
for (std::vector<int>::const_iterator j= v0.begin(); j != v0.end(); j++) 
    std::cout << *j << ' '; 

所以,如果你想使用原來的向量的保留價值,

  1. 一種方式是:a = {v0, v1, v2};
  2. 另一種方式,可以使用通過初始化陣列指針如下:

    array<vector<int> *, 3> a = {&v0, &v1, &v2}; 
    
0

tuple_assign功能:

template <class T> 
using uncvref = std::remove_cv_t<std::remove_reference_t<T>>; 

template <class T, class U, std::size_t...Is> 
void tuple_assign_(T& to, U&& from, std::index_sequence<Is...>) { 
    std::initializer_list<int>{ 
     (std::get<Is>(to) = std::get<Is>(std::forward<U>(from)), 0)... 
    }; 
} 

template <class T, class U, 
    std::size_t TSize = std::tuple_size<uncvref<T>>::value, 
    std::enable_if_t<TSize == std::tuple_size<uncvref<U>>::value, int*> = nullptr> 
T& tuple_assign(T& to, U&& from) { 
    tuple_assign_(to, std::forward<U>(from), std::make_index_sequence<TSize>{}); 
    return to; 
} 

並用forward_as_tuple包裹載體(DEMO):

tuple_assign(a, std::forward_as_tuple(std::move(v0), std::move(v1), std::move(v2))); 
相關問題