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

How do I sort a vector of pairs based on the second element of the pair?

EDIT: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type auto. This is my current favorite solution std::sort(v.begin(), v.end(), [](auto &left, auto &right) { return left.second < right.second; }); ORIGINAL ANSWER: Just use a custom comparator (it’s an optional 3rd argument to std::sort) struct … Read more

C++, copy set to vector

You need to use a back_inserter: std::copy(input.begin(), input.end(), std::back_inserter(output)); std::copy doesn’t add elements to the container into which you are inserting: it can’t; it only has an iterator into the container. Because of this, if you pass an output iterator directly to std::copy, you must make sure it points to a range that is at … 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

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)