2014-09-26 133 views
1

我必须做出“*”用绳子做,我哪里知道这个矩形string []或矢量<string>?

***** 
***** 
***** 
***** 

我不知道我应该使用哪种方法,字符串数组或字符串的向量的长度和高度的该块(或也许是第三个解决方案?)。我也想提一提,我就必须有每个“*”的访问被它的坐标,并可能改变它以下列方式

*+*+* 
***** 
++*** 
**+** 
+0

使用字符而不是字符串更好吗? – Danstahr 2014-09-26 12:22:02

+0

@Danstahr:没有,为什么会是 – Brian 2014-09-26 12:22:26

+3

如果宽度和高度是编译时间常数,考虑'的std :: array' – Deduplicator 2014-09-26 12:23:04

回答

4

vector<char>

为什么?因为这些不是真正的字符串。用2-D数据视图包装你的一维矢量,你就完成了。

如果您知道编译时的大小,则可以改为std::array

+0

岂不是'矢量>'? – matsjoyce 2014-09-26 12:24:55

+2

@matsjoyce不,由于各种原因,我猜这个评论不会包含。 SO上有很多关于这个的帖子。然而,如果我不得不挑选一个,'vector 2014-09-26 12:25:34

+0

它的规定,我使用的字符串(我需要的std :: out_of_reach例外以后)和大小是已知的 – TheGuyWithStreetCred 2014-09-26 12:36:12

1

您可以使用一类像这样的:

class Matrix 
{ 
public: 
    Matrix(int w, int h); 
    char& at(int x, int y); 
    void fill(char value); 
private: 
    int width; 
    int height; 
    std::vector<char> vec; 
}; 

// matrix.cpp 
Matrix::Matrix(int w, int h) 
{ 
    vec.reserve(w * h); 
    width = w; 
    height = h; 
} 

char& Matrix::at(int x, int y) 
{ 
    assert(x < width && y < height && "variable can't be superior to matrix size"); 
    return vec[x + y * width]; 
} 

void Matrix::fill(char value) 
{ 
    std::fill(vec.begin(), vec.end(), value); 
} 
+1

你真的只需要存储宽度或高度。 – 2014-09-26 12:24:51

+0

“变量不能超越矩阵大小”嘿嘿,这并不意味着你认为它的作用,这意味着变量不能比矩阵大小更好 – 2014-09-26 14:18:58

-1

如果有需要随机改变给定任何坐标(LINE_NO,col_no),我建议去环绕“的boost :: unordered_map < int,std :: string>“(其中int是行号,字符串是完整的字符串)。由于无序映射内部基于散列表的概念,因此性能良好。

+0

我认为这是我的触角小,因为我只是一个纯粹的初学者 – TheGuyWithStreetCred 2014-09-26 12:35:13

+0

我不觉得'unordered_map'是模拟二维数组的好方法。 – 2014-09-26 13:12:19

0

可以使用向量(动态数组)由串做出的*这个块和每个位置/坐标能够作为改编[i] [j],这意味着第i行和第j列来访问。

Outline of the code: 
     Vector<string> arr; 
    string X=" "; 
    for(k=0;k<breadth;k++)X+='*'; 
    //now push X into arr 
    for(k=0;k<length;k++)arr.push_back(X); 
     Use two for loops let i and j be the indices of row and col then u can access a particular index (say to change a * to + on 2 nd row 3rd column) as 
    arr[i][j]=arr[2][3]='+'; 
+0

你可以用什么来做什么呢? – 2014-09-26 13:53:34

+0

请澄清你的答案@soorya。 – nrussell 2014-09-26 13:54:03

+0

@nrussell:我已经修改了我的答案。如果有任何错误,请告诉我 – soorya 2014-09-26 14:23:42