2017-06-14 36 views
3

我需要進行以下的算法:的std ::列表變換和複製

(Pseudocode) 
lsi = (set_1, set_2, ..., set_n) # list of sets. 
answer = [] // vector of lists of sets 
For all set_i in lsi: 
    if length(set_i) > 1: 
     for all x in set_i: 
      A = set_i.discard(x) 
      B = {x} 
      answer.append((set_1, ..., set_{i-1}, A, B, set_{i+1}, ..., set_n)) 

例如,讓LSI =({1,2},{3},{4,5})。 ({1},{2},{3},{4,5}),({2},{1},{3},{4,5}),({ 1,2},{3},{4},{5}),({1,2},{3},{5},{4})]。

我想要做到這一點(C++),但我不能。 我的代碼:

list<set<int>> lsi {{1, 2}, {3}, {4, 5}}; 

// Algorithm 
vector<list<set<int>>> answer; 
for (list<set<int>>::iterator it_lsi = lsi.begin(); it_lsi != lsi.end(); it_lsi++) 
{ 
    for (set<int>::iterator it_si = (*it_lsi).begin(); it_si != (*it_lsi).end(); it_lsi++) 
    { 
     // set_i = *it_lsi, 
     // x = *it_si. 
     // Creating sets A and B. 
     set<int> A = *it_lsi; 
     A.erase(*it_si); // A = set_i.discard(x) 
     set<int> B; 
     B.insert(*it_si); // B = {x} 
     // Creating list which have these sets. 
     list<set<int>> new_lsi; 
     new_lsi.push_back(s1); 
     new_lsi.push_back(s2); 
     /* 
     And I don't know what should I do :-(
     Object lsi must be immutable (because it connect with generator). 
     Splice transform it. Other ways I don't know. 
     */ 
    } 
} 

你能幫我嗎? 謝謝。

+0

你不是在'answer'積累的結果嗎?我不明白你爲什麼需要在'lsi'上調用'splice'。 –

+0

考慮使用['auto'](http://en.cppreference.com/w/cpp/language/auto)和[基於範圍的循環](http://en.cppreference.com/w/cpp/language/range-for)可以極大地簡化您的示例。它將使您無需在將來寫出迭代器類型名稱。 –

+0

>我不明白你爲什麼會需要調用LSI 剪接如果接頭沒有改變'lsi',我可以這樣做: \t new_lsi.splice(new_lsi.begin(),LSI,it_lsi ); \t 不幸的是,它改變了'lsi'。 –

回答

1
list<set<int>> lsi {{1, 2}, {3}, {4, 5}}; 

vector<list<set<int>>> answer; 
for (auto it_lsi = lsi.begin(); it_lsi != lsi.end(); ++it_lsi) 
{ 
    if (it_lsi->size() > 1) 
     for (int i : *it_lsi) 
     { 
      list<set<int>> res {lsi.begin(), it_lsi}; 
      set<int> A = *it_lsi; 
      A.erase(i); 
      set<int> B {i}; 
      res.push_back(A); 
      res.push_back(B); 
      res.insert(res.end(), next(it_lsi), lsi.end()); 
      answer.push_back(res); 
     } 
} 

運行的代碼用簡單的輸出:http://ideone.com/y2x35Q

+0

謝謝,太好了。 –