Connecting Tech Pros Worldwide Forums | Help | Site Map

Problem with distance and STL map

tron.thomas@verizon.net
Guest
 
Posts: n/a
#1: Sep 13 '05
I have tried the following code on three different compilers and all
three produce programs that hang and fail to complete successfully.

#include <map>
#include <string>
#include <iostream>
#include <iterator>

int main()
{
typedef std::map<int, std::string> Values;
typedef Values::iterator Iterator;
Values values;

values[1] = "one";
values[2] = "two";
values[3] = "three";
values[4] = "four";
values[5] = "five";

Iterator first = values.find(4);
Iterator second = values.find(2);

std::cout << "The distance is " << std::distance(first, second) <<
".\n";

return 0;
}

I did not find any documentation that would indicate this should not
work.
How valid is the use of distance with an SLT map?


Ali Çehreli
Guest
 
Posts: n/a
#2: Sep 13 '05

re: Problem with distance and STL map


<tron.thomas@verizon.net> wrote in message
news:1126650388.545598.70250@o13g2000cwo.googlegro ups.com...[color=blue]
>I have tried the following code on three different compilers and all
> three produce programs that hang and fail to complete successfully.
>
> #include <map>
> #include <string>
> #include <iostream>
> #include <iterator>
>
> int main()
> {
> typedef std::map<int, std::string> Values;
> typedef Values::iterator Iterator;
> Values values;
>
> values[1] = "one";
> values[2] = "two";
> values[3] = "three";
> values[4] = "four";
> values[5] = "five";
>
> Iterator first = values.find(4);
> Iterator second = values.find(2);
>
> std::cout << "The distance is " << std::distance(first, second) <<
> ".\n";
>
> return 0;
> }
>
> I did not find any documentation that would indicate this should not
> work.
> How valid is the use of distance with an SLT map?[/color]

Like other standard algorithms, distance has no knowledge of containers. It
works with a pair of iterators. What your usage fails to meet is the
requirement that the second iterator must be reachable from the first
iterator.

Ali
--
Plug: ACCU's Silicon Valley Chapter meets on second Tuesdays. The meetings
are open to public and free of charge. Please come tonight for a talk on
Ada:

http://accu-usa.org/index.html


Pete Becker
Guest
 
Posts: n/a
#3: Sep 13 '05

re: Problem with distance and STL map


tron.thomas@verizon.net wrote:[color=blue]
>
> I did not find any documentation that would indicate this should not
> work.
> How valid is the use of distance with an SLT map?
>[/color]

For anything other than a random access iterator, distance increments
its first argument until it's equal to its second argument. Since the
first argument in the code follows the second argument, distance can't work.

--

Pete Becker
Dinkumware, Ltd. (http://www.dinkumware.com)
Closed Thread