std:: not required?

This surprised me:

std:: namespace qualifier doesn't seem to be required when using std::algorithms, such as for_each.

Example code below.

Notes:
1. I use C printf from stdio.h, since iostream includes way too much.
2. There is no "using namespace std" statement, so everything should have to be fully qualified.
3. for_each running over char * needs to be qualified by std::
4. for_each running over std::vector does not.
5. I've checked the preprocessor output (g++ -E ...) and for_each is only defined in std::, by algorithm.

So what's going on here? How does the compiler know to look in std:: for for_each?

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
#include <stdio.h>
#include <vector>
#include <algorithm>  // for_each

void
print_char(const char c)
{
  printf("%c", c);
}

	
int
main (int argc, char ** argv)
{
  
  printf("\n") ;

  printf("%s", "C string:     ");
  char  cs[15] = "I've got std::";  // extra slot for null
  std::for_each(cs, cs + 14, print_char);
  printf("\n") ;

  printf("%s", "std::vector:  ");
  char vcs[9] = "I don't!";
  std::vector<char> vs;
  vs.assign(vcs, vcs +8);
  for_each(vs.begin(), vs.end(), print_char);
  printf("\n") ;

  return 0;
}


Compiled with g++ -Wall for_each_odd.cc -o for_each_odd

For the record, the output should be:
C string:     I've got std::
std::vector:  I don't!

Oh, wow.
http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=286
All I can say is "I never would've guessed" and "I now hate using namespace more than ever".
Never would have guessed what?

The entire article is just an emotional argument. The only "fact" he gives -- about operator<<
and cout isn't quite right, because operator<< is a member function of the stream.

The very last line of the article tells me that he is obviously not a proponent of C++, so that
alone says that the article is biased.
operator<< is a member function
Oh, right.
Never mind, I think I misread something.
Thanks, R0mai. ADL explains why the C-string version has to be qualified (char * is not a struct/class in std), but vector does not.
Topic archived. No new replies allowed.