字符串[]还是向量<string>?
string[] or vector<string>?
我必须用字符串制作这个"*"块,其中我知道这个矩形的长度和高度
*****
*****
*****
*****
我想知道应该使用哪种方法,字符串数组还是字符串向量(或者第三种解决方案?)。我还想提到的是,我必须通过它的坐标访问每个"*",并可能以以下方式更改它
*+*+*
*****
++***
**+**
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是完整字符串)。它的性能很好,因为内部无序映射是基于哈希表的概念。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- EASTL矢量<向量<int>>连续的
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是std :: set&lt; std :: future&gt;不可能存在
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- ///<评论></评论>在Visual Studio中