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 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

Nice way to append a vector to itself

Wow. So many answers that are close, none with all the right pieces. You need both resize (or reserve) and copy_n, along with remembering the original size. auto old_count = xx.size(); xx.resize(2 * old_count); std::copy_n(xx.begin(), old_count, xx.begin() + old_count); or auto old_count = xx.size(); xx.reserve(2 * old_count); std::copy_n(xx.begin(), old_count, std::back_inserter(xx)); When using reserve, copy_n is … Read more

How does the capacity of std::vector grow automatically? What is the rate?

The rate at which the capacity of a vector grows is implementation dependent. Implementations almost invariably choose exponential growth, in order to meet the amortized constant time requirement for the push_back operation. What amortized constant time means and how exponential growth achieves this is interesting. Every time a vector’s capacity is grown the elements need … Read more

Correct way to work with vector of arrays

You cannot store arrays in a vector or any other container. The type of the elements to be stored in a container (called the container’s value type) must be both copy constructible and assignable. Arrays are neither. You can, however, use an array class template, like the one provided by Boost, TR1, and C++0x: std::vector<std::array<double, … 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