Why is reverse() directly usable without std:: prefix?

Consider this code snippet:
live demo: http://cpp.sh/5mymy

1
2
3
4
5
6
7
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> v {1,2,3,4};
    reverse(v.begin(), v.end()); // no need to use std::?
}


I can call reverse() without using the std:: prefix. How is this possible?

Thanks!
Last edited on
It looks to work for the C++ containers. std::vector, std::list, etc. Not including std:: will NOT work for a regular array.

Why the difference? Don't have a clue. SWAG: maybe because the C++ containers have builtin iterators.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <array>
#include <iostream>
#include <iterator>
#include <algorithm>

[code]#include <array>
#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
   std::array<int, 3> v { 1,2,3 };

   reverse(std::begin(v), std::end(v));

   for (auto e : v)
   {
      std::cout << e;
   }
   std::cout << '\n';

   int a[] = { 4, 5, 6, 7 };

   std::reverse(std::begin(a), std::end(a));

   for (auto e : a)
   {
      std::cout << e;
   }
   std::cout << '\n';
}

This example works in Visual Studio 2019.
It looks in std because the parameter (v) is from std (std::vector).
Thanks for the replies!

I digged in the standard, although it's fairly cryptic to a beginner, my guess is that the section "[basic.lookup.argdep]" (section 6.5.2 in C++20 DIS N4860) describes the behaviour. Am I correct?

For each argument type T in the function call, there is a set of zero or more associated namespaces and a set of zero or more associated entities (other than namespaces) to be considered. The sets of namespaces and entities are determined entirely by the types of the function arguments.

Surely this is a pretty confusing feature! I imagine this might cause some unwanted side effects.

Last edited on
Yes, ADL (Argument-Dependent Lookup) can be a confusing feature, and has caused headaches.
http://www.cplusplus.com/forum/lounge/263831/

mbozzi wrote:
See Herb Sutter's A Modest Proposal: Fixing ADL:
https://wg21.link/p0934
(This proposal might be dead in the water -- I don't know its status, but it gives details into some issues)
Last edited on
Very helpful links, many thanks!
Topic archived. No new replies allowed.