字符串[]还是向量<string>?

string[] or vector<string>?

本文关键字:lt gt string 向量 字符串      更新时间:2023-10-16

我必须用字符串制作这个"*"块,其中我知道这个矩形的长度和高度

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

我想知道应该使用哪种方法,字符串数组还是字符串向量(或者第三种解决方案?)。我还想提到的是,我必须通过它的坐标访问每个"*",并可能以以下方式更改它

*+*+*
*****
++***
**+**

vector<char>

为什么?因为那些不是真正的字符串。用二维数据视图包裹你的一维矢量,你就完成了。

如果您在编译时知道的大小,那么std::array可能是一个选项。

您可以使用这样的类:

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);
}

您可以使用由字符串组成的Vector(动态数组)来制作这个*块,每个位置/坐标都可以作为arr[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]='+';

如果需要随机更改给定的任何坐标(line_no,col_no),我建议使用"boost::unordereded_map<int,std::string>"(其中int是行号,string是完整字符串)。它的性能很好,因为内部无序映射是基于哈希表的概念。