jabk
jabk

Reputation: 1468

string[] or vector<string>?

I have to make this block of "*" made with string, where I know length and height of this rectangle

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

I'm wondering which approach should I use, string array or vector of strings(or maybe a third solution?). I'd also like to mention that I'll have to have an access to each "*" by it's coordinates and possibly change it in the following fashion

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

Upvotes: 1

Views: 190

Answers (4)

soorya
soorya

Reputation: 1

You can use Vector (dynamic array) consisting of strings to make this block of * and each position/coordinate can be accessed as arr[i][j] which means the i th row and j th column.

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]='+';

Upvotes: 0

ravi
ravi

Reputation: 10733

If there is need for randomly changing any co-ordinates given (line_no, col_no ) , I would suggest go and wrap around "boost::unordered_map< int, std::string >" ( where int is line no and string is complete string ). It's good performance wise as unordered map internally is based on concept of hash table.

Upvotes: -1

vincentp
vincentp

Reputation: 1433

You can use a class like this one:

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

Upvotes: 1

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39380

vector<char>.

Why? Because those aren't real strings. Wrap your 1-D vector with a 2-D data view and you're done.

If you know the size at compile time, std::array might be an option instead.

Upvotes: 4

Related Questions