Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

distance() function in C++

31 views
Skip to first unread message

Doug Mika

unread,
Apr 23, 2015, 3:34:26 PM4/23/15
to
Hi to all, I had a quick question.

I have a small simple program (I don't want to reproduce the entire thing as most likely it will be unnecessary) that has a vector<int> with some elements. It uses an iterator to find a particular value, and using the distance function it computes the distance to the located element.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

...

vector<int>::iterator iElement = find(vecIntegerArray.begin(), vecIntegerArray.end(), 2991);

//Check if the value was found
if(iElement != vecIntegerArray.end())
//Value was found...Determine position in Array
int Position = distance(vecIntegerArray.begin(), iElement);
...
}
My question is, I DID NOT include <iterator> library, what distance() function am I using in this piece of code?

Marcel Mueller

unread,
Apr 23, 2015, 3:53:50 PM4/23/15
to
On 23.04.15 21.34, Doug Mika wrote:
> #include <iostream>
> #include <vector>
> #include <algorithm>
[...]
> My question is, I DID NOT include <iterator> library, what distance() function am I using in this piece of code?

The standard library headers are allowed to include each other. So the
<iterator> include might be included indirectly by one of the others,
e.g. <algorithm>.

Of course, no program should rely on that - in fact many do so.


Marcel

Barry Schwarz

unread,
Apr 23, 2015, 5:15:41 PM4/23/15
to
You do not include libraries. You include headers.

Headers are used by the compiler. They contain the declarations for
the functions you wish to use so the compiler knows how to generate
the code to invoke those functions. (Consider the possible need to
convert an argument from int to double as in pow(2,3) or the ability
to specify default values for omitted arguments.) If you call a
function for which there is no declaration in scope, you should
receive a diagnostic.

Libraries are used by the linker. When you code a call to a function,
the compiler generates an entry in the object module that references
that function. The linker will then try to find the definition of
that function in one of the libraries it knows to look through.

There is no inherent relationship between a header and a library. It
is possible for the functions declared in a single header to be spread
out across several libraries. It is just as possible for the
functions declared in several headers to be collected into a single
library.

To answer your question, if the reference to distance was resolved by
the linker, you are using the same distance function whether you
include the <iterator> header or not. If it was not resolved, the
linker should have issued a diagnostic and you would need to inform
the linker where it should look for the function.

--
Remove del for email
0 new messages