Finding Index of Map

Hi all,

Given a map
1
2
3
4
5
6
   
map<string,double> lookup;
        lookup['foo'] = 1; 
        lookup['bar'] = 0.3; 
        lookup['qux'] = 0.4; 
        lookup['tex'] = 0.4; 


and a vector that contain
 
 {"foo", "tex"},


How can I make this function to return the index' in map
printing : 0, 3 ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

// This function of mine doesn't seem to work

vector <int> getIndexFromMap(std::vector <string> &myList, map<string,double>&m) {
    vector <int> foundIndex;

    for (int i = 0; i< myList.size() ; i++ ){
        map<string,double>::iterator iter = m.find(myList[i]);

            for ( int k =0 ; k < m.size() ; k++ ) {

            if (iter->first == myList[i]) {
                cout << "K " << k << ","; 
                foundIndex.push_back(k);
             }

        }


    }

  return foundIndex;
}


Yes, I want to use map instead of vector for this task.
Because I the map also used in other parts of my code.
Also since the size of Map is very2 large. I prefer not to
have another variable for storing them.
Last edited on
std::distance( start, end )

returns the linear distance between two iterators. The iterators must be in the same container, and start must come "before" end. (ie, it must be possible to increment start and eventually reach end).

However that turns the lookup algorithm into an O(n) algorithm that will run slower than a linear search on any unordered container.
I'm also wondering why one would want such an index for anything. A map is internally sorted; it maintains it's own order and does not guarantee anything about the validity of an index/offset for its elements. The index sounds useless.

It might be time for a better look at your design.
Last edited on
The if() check on line 12 will always be true.
How using an iterator to the element in the map rather than a numeric index?
Topic archived. No new replies allowed.