c++中的vector下标超出了非空vector的范围
C++ vector subscript out of range only with non-empty vector
在下面提到的代码的"insert"函数中,我得到的错误向量下标超出了范围":
// this acts as the vertex of graph
typedef struct node
{
string name; // stores the unique name of the vertex
int value; // stores the integer data saved in the vertex
} node;
class graph
{
private:
// 2D vector to store the adjencey list of the graph
vector< vector<node> > adjList;
public:
graph()
{
adjList.resize(0);
}
// function to insert a vertex in graph.
// 'nName' : unique name of vertex;
// 'nValue': int data stored in vertex;
// 'neighbours': string vector containing names of all neighbours
void insert(string nName, int nValue, vector<string> neighbours)
{
int i= adjList.size();
adjList.resize(i + 1);
adjList[i].resize( neighbours.size() + 1);
adjList[i][0].name = nName;
adjList[i][0].value = nValue;
string temp;
for(int nTrav=0, lTrav=1, size=neighbours.size(); nTrav<size; ++nTrav, ++lTrav)
{
temp=neighbours[nTrav];
int j=0;
for(; j<adjList.size() || adjList[j][0].name != temp; ++j);
if(j==adjList.size())
{
cout << "nName not present. Element not inserted";
return;
}
adjList[i][lTrav].name = adjList[j][0].name;
adjList[i][lTrav].value = adjList[j][0].value;
}
}
};
当传入的字符串vector 'neighbour'为空时,代码正常工作,但当vector包含某些元素时,则给出指定的错误。
操作系统:Windows 8IDE: Visual Studio 2013
除了Joachim对vector.push_back(...)
的评论之外,您应该将第二个循环更改为:
for(; j<adjList.size() && adjList[j][0].name != temp; ++j)
用AND代替OR。在评估其内容之前,您必须确保满足j<adjList.size()
条件。否则,由于延迟计算,当j<adjList.size()
返回false时,您实际上只计算adjList[j][0].name != temp
。
相关文章:
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 如果变量数据包含大于 vector 所有元素的整数,则仅在视觉工作室上接收"矢量下标超出范围"?
- 使用范围库初始化 std::vector
- 示例代码中使用分隔符将 std::string 拆分为 std::vector 的范围问题
- 将视图范围设置为std::vector
- std::vector 范围构造函数可以调用显式转换吗?
- 基于 C++ 范围的 std::vector 迭代的顺序
- C++ 如何在 std::vector 中插入一个连续的间隔范围?
- 在基于范围的循环中使用shared_ptr到std :: vector
- std::vector<std::vector<int>>:调试断言失败。C++矢量下标超出范围保留内存
- 在<Object>基于范围的 for 循环中从 std::vector 获取指向对象的指针
- 为什么此代码会给出 Vector 超出范围错误
- "vector"未在此范围内声明
- 我的程序正在抛出一个错误,声称Vector下标超出了范围.(C )
- 基于范围的loop和std :: vector.push_back()崩溃了程序
- C 内存管理问题,std :: vector nevere rase内存超出范围
- 使用范围检查和带符号的size_type扩展std::vector
- 擦除范围从std :: vector删除向量的最佳方法
- 当第一个 itr 在最后一个 itr 之后时,std::vector 范围构造函数的官方行为是什么?
- 在 std::vector 中插入迭代器范围