c++ - Pointer Problems in Vector -


i trying brush on c++ since has been while since used , i'm having problem storing pointers. @ end of method below, vector "graph" has of vertices inserts, edges supposed added corrupt (i can see edges in debugger, data garbage). wondering if guide?

thanks!

for reference, add_edge function declared follows:

std::vector<vertice*> m_edges;     ...     ... void add_edge(vertice* n); {     m_edges.push_back(n); } 

the primary problem:

std::vector<vertice> graph; std::string line;  //iterate on line int linecount = 0; while(getline(file, line)) {     auto vertices = parse_line(line);     for(size_t = 0; < vertices.size(); ++i)     {         auto result = std::find_if(             graph.begin(),             graph.end(),             [&] (vertice cvert) { return cvert.getname() == vertices.at(i); });          std::vector<vertice>::size_type currpos =              std::distance(graph.begin(), result);          if(result == graph.end())         {             graph.emplace_back(vertice{vertices.at(i)});         }          if(i == 0) { continue; }         graph.at(linecount).add_edge(currpos == graph.size() ?              &graph.back() : &graph.at(currpos));     }      ++linecount; }  //the vector graph has corrupt nodes here 

pointers content of std::vector may invalidated when insert new elements, such in std::vector::emplace_back:

if new size() greater capacity() iterators , references (including past-the-end iterator) invalidated. otherwise past-the-end iterator invalidated.

consider std::vector::reserve reserve capacity before needing reallocate elements or use different container, 1 not invalidate references on insert, perhaps std::list.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -