C++中的 2d 矢量插入

2d Vector Insertions in C++

本文关键字:插入 2d 中的 C++      更新时间:2023-10-16

目前正在使用向量向量处理图形表示。 我正在尝试在adjacencies内的特定位置插入边缘向量。 adjacencies定义为adjacencies = new std::vector< std::vector<Edge*>* >;

我遇到了矢量未在特定.stateId位置插入的问题。 逻辑很可能不是我想要的。 我需要调整矢量大小吗? 从文档中,我假设矢量在当前不在矢量中的位置插入时会自动调整大小。 我很感激你的澄清。

这是我的方法:

/*
 * Connecting Edge vertF -----> vertT via weigh
 * adjacencies[v][e]
 */
void GraphTable::InsertEdgeByWeight(Vertex* vertF,Vertex* vertT, char weigh){
        Edge* tempEdge = new Edge(vertT,weigh);
        /*
         * Need to figure out how to properly allocate the space in adjacencies.size()
         * Test 4 works with initial ID 0 but not test 5 with ID 4
         */
         std::vector<Edge*>* temp_vec = new vector<Edge*>;
         temp_vec->push_back(tempEdge);
            /*if vector at location doesnt exist, we will push a new vector of edges otherwise we
             * will need to push the edge into the current vector
             */
         if(adjacencies->size()<vertF->thisState.stateId){
             adjacencies->resize(vertF->thisState.stateId);
             adjacencies[vertF->thisState.stateId].push_back(temp_vec);
         }else{
            adjacencies[vertF->thisState.stateId].push_back(temp_vec);
         }
        cout<< adjacencies->capacity() << endl;
        //cout<< adjacencies->max_size() << endl;
}

您正在将adjacencies的大小调整为 vertF->thisState.stateId 值,然后调用 adjacencies[vertF->thisState.stateId]
如果向量/数组的大小为"x",则最高索引为"x-1"。

所以你应该写这个代替 - :

adjacencies[vertF->thisState.stateId-1].push_back(temp_vec);

编辑 :正如 Ankit Garg 在评论中指出的那样,您可能应该将tempEdge直接推送到adjacencies而不是创建临时向量。

从我的评论中扩展,我认为您必须执行以下操作:

if(adjacencies->size() < vertF->thisState.stateId)
{
    // the vector does not exist, hence push_back the new vector
    .....
}
else
{
    // vector already exists, so just push_back the edge
    adjacencies[vertF->thisState.stateId].push_back(temp_edge);
}