我无法初始化结构值C++
I can't initialize a struct values in C++
我有这个变量:
struct mat{
int row;
int column;
};
vector<bool> aux;
在主函数中,我通过以下方式初始化 mat 的向量:
int main(){
int n,r,c;
char s;
cin >> n;
vector<mat> matrices = vector<mat> (27);
aux = vector<bool> (32,false);
for(int i=0; i<n;++i) {
cin >> s >> r >> c;
matrices[s-'A'].row = r;
matrices[s-'A'].column = c;
aux[s-'A'] = true;
}
但是当我离开for
循环时,我调用了一个函数,该函数在 shell 中写入向量矩阵:
void writeMatrices(vector<mat>& matrices){
for(int i = 0; i < aux.size(); ++i){
if(aux[i]) {
cout << char ('A'+i) << " Rows: " << matrices[i+'A'].row << " Columns: " << matrices[i+'A'].column << endl;
}
}
}
而且我只得到0。
有人知道为什么吗?
问题是您在读回索引时错误地将 'A'
的值添加到索引中。 writeMatrices
的代码应该是这样的:
void writeMatrices(vector<mat>& matrices){
for(int i = 0; i < aux.size(); ++i){
if(aux[i]) {
cout << char ('A'+i)
// note that the index for matrices should be i, not i+'A' !
<< " Rows: " << matrices[i].row
<< " Columns: " << matrices[i].column
<< endl;
}
}
}
与此输入数据一起使用:
6
A 1 2
B 2 3
C 3 4
D 4 5
E 5 6
F 6 7
我们现在得到这个输出:
A Rows: 1 Columns: 2
B Rows: 2 Columns: 3
C Rows: 3 Columns: 4
D Rows: 4 Columns: 5
E Rows: 5 Columns: 6
F Rows: 6 Columns: 7
代码中的一些错误检查将使您能够更快地发现此问题。
矩阵集合有 27 个元素。 您的 bool (aux) 集合有 32 个元素,这比大小或矩阵集合还要多。 您的 for 循环正在执行"n"次,这可能是任何取决于输入的内容。 您的集合索引器是"s-'A'",我假设您输入的是"A,B,C,D,..." 总而言之,这是一种非常奇怪、随意和不可靠的处理集合的方式。 相反,您应该只有 1 个最大大小和 1 个循环索引器变量,并将其用于所有内容。 或者从空集合开始,然后使用"push_back()"添加每个元素。 您还可以添加"bool aux"作为"mat"结构的成员,这样就不需要单独的"aux"集合了。
您给出的代码中也没有设置"r"和"c"的内容,因此除非在未显示的代码中设置了这些设置,否则您只会将行和列字段设置为默认值 r 和 c。
在 for 循环中,您使用了向量矩阵的索引s-'A'
for(int i=0; i<n;++i) {
cin >> s >> r >> c;
matrices[s-'A'].row = r;
matrices[s-'A'].column = c;
aux[s-'A'] = true;
}
正如我猜的那样,s 的值在"A"-"Z"范围内
但是在函数内部,您使用了向量矩阵的索引"i+"A"
cout << char ('A'+i) << " Rows: " << matrices[i+'A'].row << " Columns: " << matrices[i+'A'].column << endl;
我认为向量矩阵中的索引必须与向量辅助中的索引相吻合。这就是函数的主体应该看起来像
void writeMatrices( const vector<mat> &matrices )
{
for ( std::vector<bool>:size_type i = 0; i < aux.size(); ++i )
{
if( aux[i] )
{
cout << char ('A'+i) << " Rows: " << matrices[i].row << " Columns: " << matrices[i].column << endl;
}
}
}
我认为容器std::map<char, mat>
更适合您的任务。
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 多成员Constexpr结构初始化
- C++将文本文件中的数据读取到结构数组中
- 如何重构类层次结构以避免菱形问题
- 如何在C++中序列化结构数据
- std::vector的包装器,使数组的结构看起来像结构的数组
- 没有为自己的结构调用列表推回方法
- 奇怪的结构&GCC&clang(void*返回类型)
- 在 c++ 中拥有一组结构的正确方法是什么?
- vscode g++链路故障:体系结构x86_64的未定义符号
- C++概念:如何使用'concept'检查模板化结构的属性?