C ++中的2d向量插入

时间:2015-03-07 04:50:25

标签: c++ vector

目前正在使用向量向量进行图表表示。我试图在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;

}

2 个答案:

答案 0 :(得分:3)

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

所以你应该写这个 - :

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

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

答案 1 :(得分:0)

从我的评论中扩展,我认为你必须做这样的事情:

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);
}