简体   繁体   English

c++向量元素访问

[英]c++ vector elements access

I am trying to create a vector with a datatype I have already defined in a class我正在尝试使用我已经在类中定义的数据类型创建一个向量

vector<MYdatatype> myVector;

but when I try to access the elements in the vector using a for loop但是当我尝试使用 for 循环访问向量中的元素时

for(int i=0; i<myVector.size();i++)

I get an error message telling that the vector is out of range Debug assertion failed line 932!我收到一条错误消息,告知向量超出范围调试断言失败第 932 行!

THIS IS MY CODE这是我的代码

vector <Road_Segment> Unvisited;//the vector

for (i = 0; i<Unvisited.size(); i++)
{
    cur_node = Unvisited[0];//current node to visit

    find_node_neighbers(cur_node.end_station.ID, end, T_R);

when I try to comment this for loop I don't get that error message当我尝试对此循环进行评论时,我没有收到该错误消息

any help would be appreciated任何帮助,将不胜感激

This line:这一行:

cur_node = Unvisited[0];

should really be:真的应该是:

cur_node = Unvisited[i];

Otherwise, it will just access the first element over and over.否则,它只会一遍又一遍地访问第一个元素。

But if you just need to perform an action on each element, you should use a foreach loop instead:但是如果你只需要对每个元素执行一个操作,你应该使用 foreach 循环:

for (const Road_Segment& cur_node : Unvisited) {
  // I'm guessing "neighbers" is just a typo, but that's what was in the question
  find_node_neighbers(cur_node.end_station.ID, end, T_R);
}

This allows you to avoid any problems with indices and such.这使您可以避免索引等方面的任何问题。 Or if you need to actually modify each element instead of just using it, simply remove the const :或者,如果您需要实际修改每个元素而不是仅仅使用它,只需删除const

for (Road_Segment& cur_node : Unvisited) {
  // do something that modifies cur_node
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM