我无法初始化结构值C++

I can't initialize a struct values in C++

本文关键字:C++ 结构 初始化      更新时间:2023-10-16

我有这个变量:

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>更适合您的任务。