C++中的 2d 矢量插入
2d Vector Insertions in C++
目前正在使用向量向量处理图形表示。 我正在尝试在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);
}
相关文章:
- 在将字符插入 2d 字符串时如何不显示空字符?
- 如何仅使用其中一个维度在 2D 矢量中插入值?
- 如何从队列插入到 2D 列表
- C++2D网格数组,从文件中读取和插入数组值
- 如何在不通过插入排序更改原始矢量的情况下对 2D 矢量进行排序
- 无法使用push_back将整数插入1D/2D向量
- 将 2D 数组插入 std::vector 时"cannot convert from 'const GLfloat [12]' to '_Objty'"错误消息
- 将文本文件插入2D矢量C
- 如何插入一个单词并将字母放在2D数组中的不同索引中
- 如何在其中创建2D字符串向量并插入数据
- 如何将向量插入2D矢量的定义位置
- C++中的 2d 矢量插入
- 如何从文件中将名称插入2D字符数组
- 在 2D 图像阵列中裁剪/插入 - 内存分配问题
- 将字符串列表插入 2D 矢量
- 将元素插入 2D 矢量C++
- 将元素插入 2D 矢量
- 将多个元素插入到 2D 块中
- 插入 2D 矢量的特定位置
- 将1D矢量插入2D矢量而不创建Temp 1D矢量