The code you posted will not compile yet (no tmp declared in the first loop), so let me explain in general what is going on.
You mentioned two types of errors:
vec.at(i).setVec(tmp); //Works sometimes or causes error std::out_of_range
The at function tries to be safe - it first checks the length of the vector, then returns an element of the given index or throws std::out_of_range if the vector does not contain an element of such an index.
Second case:
vec[i].setVec(tmp);
The operator [] behaves in the same way as the at() function for vectors, but it is not "safe" because it does not fulfill any restrictions. Therefore, if you try to access the 4th element from a 3-element, you just get access to some random place in your memory (maybe, for example, another, unrelated variable, maybe something else). If you're lucky, then your program will crash. If you're out of luck, you will have memory corruption issues and very strange errors that are hard to find.
The solution to your problem:
a) Replace vec[i] with vec.at(i) - work the same way (well, a tiny bit is slower, but you wonโt feel it), and you are safe.
b) Then: Look at all the places when you really do this vector search and stop at each second for a second and think: "How big is this vector at this moment? Am I sure that an element of this index exists?"
You will probably find your mistake quickly.
source share