2013-11-25 24 views
0

任何地方我有一個方形2dvector(網格),我要插入到它的零的數量(「濃」)。 然後,洗牌矢量以分發零。 (假設網格矢量大小爲10x10)。分發數量的零在網格

1)I嘗試:

 int conc=1; 

     for (size_t i=0, max=conc; i!=max;i++){ 
       grid.erase(grid.begin()+1); 

      for (size_t j=0,max=grid.size();j!=max; j++) 
       grid[i][j]=0; 
      } 


      random_shuffle(grid.begin(),grid.end()); 

的問題是,與上述我收到10個零(網格尺寸= 10×10)代替1-(現在濃度= 1,所以想要1爲零)。

和十個零點都在一個row.I想在網上的任何地方分配零的個數。

我想插入1個零(濃度)。

+2

您可能想要閱讀['std :: random_shuffle'引用](http://en.cppreference.com/w/cpp/algorithm/random_shuffle)。 –

+0

'的std :: random_shuffle'沒有返回 – P0W

+0

@Joachim Pileborg:我查過,但在2D矢量我沒有管理,使其工作。 – George

回答

1

您可以使用像這樣的數組:

arr[LINES*COLUMNS] 

代替

arr[i][j] 

訪問,並作爲

arr[i*COLUMNS+j] 

使用這種方法,一切都是線性的,假設你要這樣行爲爲您洗牌...

UPDATE

AMD作爲約阿希姆Pileborg建議...閱讀更多有關random_shufle ...

0
//is this what you intended 
int conc=10; 
for (size_t i=0, max=grid.size(); i!=max;i++){ 
      for (size_t j=0,max=grid.size();j!=max; j++) 
       grid[i][j]=conc;//change here 
      } 
+0

:我想用「濃」零填充數組。例如10個零。 – George

+0

@George十個零是什麼意思?你的意思是它必須在矩陣'grid'中的任何地方都有十個零? – P0W

+0

@George似乎你在填充整個數組結構之前的值爲零。你已經在那裏成功了嗎?除了您關心的零是否還有其他一些價值是您的要求的一部分?你可能想要做一些容易的事情。我們只需要瞭解你需要什麼。 –

0

std::random_shuffle返回任何

使用算法

後,您應該只顯示矩陣
random_shuffle(&arr[0][0], &arr[0][0] + sizeof(arr)/sizeof(arr[0][0])); 

for(std::size_t i = 0; i < 4; ++i) 
{ 
for(std::size_t j = 0; j < 2; ++j) 
    std::cout << arr[i][j] << " "; 
std::cout << std::endl; 
} 
+0

:嗯,它運行,但shuffle沒有WORL爲expected.I想從ARR返回一個元素,但它可能會返回,例如「1 1「,這在arr中不存在!另外,我的意思是10個零,我想添加到網格10個零,然後洗牌矢量。 – George

+0

@George [什麼不行?](http:// ideone。com/uwTk3U)使用適當的種子值 – P0W

+0

:好的,至於洗牌,錯誤是使用arr [0] [0],我們必須使用arr [0]。至於我的其他問題,如果你可以幫助。我欣賞它。謝謝 – George

0
//I do not want to violate your constraints and 
//if you are willing to encapsulate something 
//we can let the compiler deal with size observations about an old fashioned array 
struct pairx 
{ 
    int d[2]; 
}; 

int a_test_200() 
{ 
pairx x{{4,3}};//notice more braces ..used only for explanation to human 
//also consider std::vector if your constraints permit 
pairx arrp[]={ { {0,1}},{ {1,0}}, { {0,-1}}, { {-1,0} } }; 
cout << "original" << endl; 
for (const auto & e : arrp) cout << e.d[0] << " " << e.d[1] << ", "; 
cout << endl; 
//we assume you shuffle opaque structure pairx 
random_shuffle(begin(arrp), end(arrp)); 
cout << "shuffle" << endl; 
for (const auto & e : arrp) cout << e.d[0] << " " << e.d[1] << ", "; 
cout << endl; 
return 0; 
} 
+0

@George這個封裝的方法可能會保留你對數據的概念......這裏寫成pairx。這是參考您的評論關於洗牌比你想要的更多。 –