0

Trying to brush up on my C++, I picked up a helper function I needed from a web search and tried it out before looking it up in the C++ reference:

int count_vowels(const std::string &input) {
    return std::count_if(input.begin(), input.end(), is_vowel);
}

When I looked up more details on count_if(), I found that it's part of the <algorithm> library code (http://www.cplusplus.com/reference/algorithm/count_if/), which I had not included when I compiled and ran it. Why would the function work without the <algorithm> header? I have included <iostream>, <string> (obviously) and <sstream<>. And I'm using the compile flag -std=c++11 if that matters at all.

Also, if it works without the <algorithm> header, should I put that header in anyway for clarity's sake (or because other compilers wouldn't necessarily pick up the necessary function definition)?

Marshall Farrier
  • 947
  • 2
  • 11
  • 20

2 Answers2

6

It works because it's probably included indirectly via one of the other headers. It's not guaranteed though, and it might break on a different compiler, or a future version of the one you're using now.

Include all the headers you need directly.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

If you are using Visual C++ then you can turn on show includes to see what files are included, via Project -> Settings -> C/C++ -> Advanced.

If using gcc then this explains the equivalent: /show include equivalent option in g++

You will then know where it is being included.

Community
  • 1
  • 1