c++ - Why are appended vectors throwing away data? -



c++ - Why are appended vectors throwing away data? -

i have number of vectors contained within 1 big vector pointers. i'd merge vectors in list based on arbitrary condition. involves first appending 2 vectors together, removing 1 of them "large" vector.

when run program, case vector of length 6 , 12 merged together, giving total length of 12 (thus throwing away 6 elements).

i've tried recreate problem in 1 contained c++ file. didn't quite manage (this 1 throws non-debuggable index out of bounds error). far can tell i'm messing number of things here.

#include <stdio.h> #include <math.h> #include <iostream> #include <fstream> int main(int argc, char** argv) { std::vector<std::vector<int>*> lists; //create lists variable size for(int = 0; < 100; i++) { std::vector<int> vec; for(int j = 0; j < i; j++) { vec.push_back(j); } lists.push_back(&vec); } //do merging bool changed = true; while(changed) { changed = false; for(int list = 0; list < (int)lists.size(); list++) { std::vector<int>* listinstance = lists.at(list); for(int otherlist = 0; otherlist < (int)lists.size(); otherlist++) { if(list == otherlist) {//avoid merging lists continue; } std::vector<int>* otherlistinstance = lists.at(otherlist); if(lists.at(otherlist)->size() % 4 == 0) { //some arbitrary status merging. changed = true; int othersize = otherlistinstance->size(); listinstance->insert(listinstance->end(), otherlistinstance->begin(), otherlistinstance->end()); lists.erase(lists.begin() + otherlist); if(othersize != otherlistinstance->size()) { std::cout << "does not match!\n"; } otherlist--; } } } } homecoming 0; }

you pushing pointers local variables. that's undefined behavior.

change

std::vector<std::vector<int>*> lists; //create lists variable size for(int = 0; < 100; i++) { std::vector<int> vec; for(int j = 0; j < i; j++) { vec.push_back(j); } lists.push_back(&vec); }

to

std::vector<std::vector<int>> lists; //create lists variable size for(int = 0; < 100; i++) { std::vector<int> vec; for(int j = 0; j < i; j++) { vec.push_back(j); } lists.push_back(vec); }

or create non-local version using new.

std::vector<std::vector<int> *> lists; //create lists variable size for(int = 0; < 100; i++) { std::vector<int> * vec = new std::vector<int>(); for(int j = 0; j < i; j++) { vec->push_back(j); } lists.push_back(vec); }

of course of study improve utilize std::vector<std::shared_ptr<std::vector<int> > > type lists. way, not need manual memory management.

c++

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -