Problem with distance and STL map

T

tron.thomas

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?
 
P

Pete Becker

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

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.
 
?

=?iso-8859-1?Q?Ali_=C7ehreli?=

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?

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top