1

These members of below headers(there may be more) don't need std namespace but works with std:: also

<algorithm>
  find() vs std::find(), for_each() vs std::for_each()
<numeric>
  accumulate() vs std::accumulate()

Please consider below small program, its here too: https://wandbox.org/permlink/1YxUNYdrFhCZc6qu

//using namespace std; is not present in this program
//we must write std::cout can't just write cout
//but std::find and find both works same is true about for_each 
#include <iostream>
#include <vector>
#include <algorithm>
void printer(int e) { std::cout << e << " "; }
int main()
{
    std::vector<int> v = {1, 2, 4, 7};
    std::vector<int>::iterator it;
    //find
    it = find(v.begin(), v.end(), 4);
    std::cout <<"1] Found: " << *it << '\n';
    //std::find
    it = std::find(v.begin(), v.end(), 4);
    std::cout <<"2] Found: " << *it << '\n';
    std::cout << "Printing all elements:\n";
    //for_each
    std::cout << "1] ";
    for_each(v.begin(), v.end(), printer);
    //std::for_each
    std::cout << "\n2] ";
    std::for_each(v.begin(), v.end(), printer);

    return 0;
}

Why is it so ? I have tried both g++ and clang, same output.

Sumit
  • 1,485
  • 11
  • 24
  • Officially, you always need `std`. I knew some standard headers would add C-type methods to the global namespace, but I'm shocked that any template methods like `find` compile. – Mooing Duck Apr 20 '20 at 22:47
  • 2
    Is it because of ADL? I'm so used to specifying exactly what I want I never noticed it might work without. https://stackoverflow.com/questions/8111677/what-is-argument-dependent-lookup-aka-adl-or-koenig-lookup – Retired Ninja Apr 20 '20 at 22:48

0 Answers0