Reading and writing a std::vector into a file correctly

Try using an ostream_iterator/ostreambuf_iterator, istream_iterator/istreambuf_iterator, and the STL copy methods: #include <algorithm> #include <iostream> #include <iterator> #include <vector> #include <fstream> // looks like we need this too (edit by π) std::string path(“/some/path/here”); const int DIM = 6; int array[DIM] = {1,2,3,4,5,6}; std::vector<int> myVector(array, array + DIM); std::vector<int> newVector; std::ofstream FILE(path, std::ios::out | std::ofstream::binary); std::copy(myVector.begin(), myVector.end(), … Read more

Performance issue for vector::size() in a loop in C++

In theory, it is called each time, since a for loop: for(initialization; condition; increment) body; is expanded to something like { initialization; while(condition) { body; increment; } } (notice the curly braces, because initialization is already in an inner scope) In practice, if the compiler understands that a piece of your condition is invariant through … Read more

How do I sort the texture positions based on the texture indices given in a Wavefront (.obj) file?

If there are different indexes for vertex coordinates and texture coordinates, then the vertex positions must be “duplicated”. The vertex coordinate and its attributes (like texture coordinate) form a tuple. Each vertex coordinate must have its own texture coordinates and attributes. You can think of a 3D vertex coordinate and a 2D texture coordinate as … Read more

vector::at vs. vector::operator[]

I’d say the exceptions that vector::at() throws aren’t really intended to be caught by the immediately surrounding code. They are mainly useful for catching bugs in your code. If you need to bounds-check at runtime because e.g. the index comes from user input, you’re indeed best off with an if statement. So in summary, design … Read more

Is std::vector copying the objects with a push_back?

Yes, std::vector<T>::push_back() creates a copy of the argument and stores it in the vector. If you want to store pointers to objects in your vector, create a std::vector<whatever*> instead of std::vector<whatever>. However, you need to make sure that the objects referenced by the pointers remain valid while the vector holds a reference to them (smart … Read more

How to remove duplicates from unsorted std::vector while keeping the original ordering using algorithms?

Sounds like a job for std::copy_if. Define a predicate that keeps track of elements that already have been processed and return false if they have. If you don’t have C++11 support, you can use the clumsily named std::remove_copy_if and invert the logic. This is an untested example: template <typename T> struct NotDuplicate { bool operator()(const … Read more