c - 将 1D vector 中的元素添加到 2D vector

标签 c loops vector

我有一个名为 geoData 的 1D vector ,然后有一个名为 redVec 的 2D vector ,其中包含用户定义的行和列。我想将 1D vector 中的元素添加到 2D vector 中,但在 xCode 中出现错误访问错误。

for(int r = 0; r < numRows; ++r){
    for(int c = 0; c < numCols; ++c){
        for(int i = 0; i < geoData.size(); ++i){
            redVec[r][c] = geoData.at(i);
        }
    }
}

最佳答案

首先,你是否用适当的大小初始化你的 redVec 和每个内部 vector (!)?其次,你最里面的循环做了奇怪的事情。您可能想要类似的东西

for(int i = 0, r = 0; r < numRows; ++r){
    for(int c = 0; c < numCols; ++c){ 
        redVec[r][c] = geoData.at(i);
        i++; // increase i each time new cell is filled
    }
}

或者即使您没有事先创建所需大小的 vector

for(int i = 0, r = 0; r < numRows; ++r){
    vector<whatever_type_you_have> row = vector...
    for(int c = 0; c < numCols; ++c){ 
        row.push_back(geoData.at(i))
        i++; // increase i each time new cell is filled
    }
    redVec.push_back(row)
}

关于c - 将 1D vector 中的元素添加到 2D vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42538333/

相关文章:

c++ - 为什么这个循环每次都向 sqdNumber_result 输出 0?

c++ - std::sort vector 的 vector

c - 将 objconv 与 ld 而不是 gcc 一起使用

c - printf 不在 eclipse c 的控制台中打印

javascript - 如何从数组中的数据创建对象中的键?

math - 非规范化向量

python - 查找文档中句子之间的语义相似性

c - 对符号 'CERT_GetDefaultCertDB@@NSS_3.2' 的 undefined reference

c - 关于结构中的内存对齐和 sizeof 运算符的可移植性的问题

c - 如何在 C 中使用带有用户输入的循环函数?