Element at index in a std::set?

It doesn’t cause a crash, it just doesn’t compile. set doesn’t have access by index. You can get the nth element like this: std::set<int>::iterator it = my_set.begin(); std::advance(it, n); int x = *it; Assuming my_set.size() > n, of course. You should be aware that this operation takes time approximately proportional to n. In C++11 there’s … Read more

Can a declaration affect the std namespace?

The language specification allows implementations to implement <cmath> by declaring (and defining) the standard functions in global namespace and then bringing them into namespace std by means of using-declarations. It is unspecified whether this approach is used 20.5.1.2 Headers 4 […] In the C++ standard library, however, the declarations (except for names which are defined … Read more

Syntax for using std::greater when calling std::sort in C++

Why are there parentheses after std::greater there? Are we creating a new std::greater object here? That’s correct. The expression std::greater<int>() corresponds to creating an object of type std::greater<int>. In that case, why don’t we need the new keyword here? We don’t need the new keyword because the object is being created on the stack, rather … Read more