2011-11-11 297 views
1

我們給出了一些int el_position號碼,這是我們想要的一個位置,通過我們的二維矢量(std::vector< std::vector<int> > matrix(5, std::vector<int>(4)))的flatened表示。如何到達2d std :: vector的第N個元素(`std :: vector <std :: vector <T>>`)?

含義,如果我們有這樣的矩陣

11 21 31 41 51 
61 71 81 91 101 

,我們分別給予el_position==7,我們需要得到第二排的第二個元素。是否有可能用std 2d向量做這樣的事情?如何通過給定在扁平數組中的位置來獲取元素的值?

回答

3

相信這是可能的:

row = el_position % row_length; 
col = el_position/row_length; 
3
size_t size_y = matrix.front().size(); // to get your Y dimension 
return matrix[el_position/size_y][el_position % size_y]; 
+0

但是,正如我在我的回答中指出的那樣,要注意'matrix.front()。size()'來產生你需要的值。 –

+0

@ MichaelKrelin-hacker:同意了,爲了避免任何可能的麻煩,我建議在C++ 11('std :: vector >') –

+0

'std :: vector '也許是比較全面的? –

2

你只取n/W一個索引,而另一個 - n%W,其中W是寬度(或行長度,等等)。請注意,實際上,在矢量矢量中,您可能具有不同長度的矢量,所以它是由你來分解的。

1
// Assuming fixed dimensions: 
matrix[el_position/size][el_position%size]; 

/是整數除法,所以計算,我們必須通過找到行,我們正在尋找和%完整的行數是餘從整數除法,所以我們應該找到多遠,以抵消行。

如果你的一個內部矢量的大小不一樣,這將失敗。你可以用兩個斷言來檢查這個假設:

assert(matrix.size()); // needed for the front element to be valid 
assert(std::count(matrix.begin(), matrix.end(), matrix.front().size()) 
     == matrix.size()); // the count will be the number of elements 
          // if it's correct 
相關問題