Reputation: 4328
How can i directly find the number of elements between any two iterator pointing to two different key in map without the for loop?
#include <string>
#include <iostream>
#include <map>
#include <utility>
#include <iterator>
#include <stdio.h>
using namespace std;
int main()
{
std::map<string, string> m;
m.insert(pair< string, string>("4-2"," 61-7" ));
m.insert(pair< string, string>("5-2"," 61-7" ));
m.insert(pair< string, string>("5-3"," 61-7" ));
m.insert(pair< string, string>("5-4"," 61-7" ));
m.insert(pair< string, string>("5-5"," 61-7" ));
m.insert(pair< string, string>("5-6"," 61-7" ));
map<string, string>::iterator it4;
map<string, string>::iterator it5;
it4=m.find("5-2");
it5=m.find("5-5");
cout << " value of it4" << it4->first << it4->second << endl;
cout << " value of it5" << it5->first << it5->second << endl;
m.clear();
getchar();
}
My desired output is difference of elements betwen it5 and it4 which here is 2 as elements with key "5-3" and "5-4" lies between them . I dont want to iterate in for loop as in my case number of elements in map are large enough . And I have to regularly know the difference . using a for loop will take lot of time if two iterator are far away .
Upvotes: 0
Views: 179
Reputation: 247919
Given your requirements, it can't be done. std::map
does not offer random-access iterators, which are necessary for determining iterator distance in constant time.
You can still use std::distance
, but the cost will be the same as if you wrote the loop yourself.
If you need to generate this information more efficiently, you'll have to replace the map with a different data structure (or at least, augment it with some additional bookkeeping).
The only standard-library containers which have random-access iterators are the vector
, deque
and `array.
Upvotes: 1
Reputation: 476990
You can use std::distance(it4, it5)
from <iterator>
. The cost will be linear in the result, though, so that doesn't really save you. If you must have quick access to this information, consider a Boost.Multi_index container so you can add a random-access index to your map.
Upvotes: 5