tags:

views:

153

answers:

2

i created a map. i want to print the index of the key to a file using the itr in the map. this is what i mean:

map <string,int> VendorList;  
VendorList[abc] = 0;
VendorList[mazda] = 111;
VendorList[ford] = 222;
VendorList[zoo] = 444;
map <string,int>::iterator itr=VendorList.find("ford");
fstream textfile;
textfile << itr;

if i put in the find line abc i wish the program to cout 1.

if i put in the find line mazda i wish the program to cout 2.

if i put in the find line ford i wish the program to cout 3.

if i put in the find line zoo i wish the program to cout 4.

how do i do that? the compiler is shouting on the line:

 textfile << itr;

it gives this error: error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::_Tree<_Traits>::iterator' (or there is no acceptable conversion)

+2  A: 

In map, the elements aren't stored in the order of insertion, so you have to hold the "order" data yourself.

I would suggest you to consider using a vector of pairs instead of a map. Vector does store the elements in the order of insertion, and its iterator is Random-Access so you will be able to check the position using the operator-.

vector <pair<string, int> >::iterator itr;
// itr = the needed element
cout << itr - VendorList.begin();
Igor Oks
+6  A: 

Your program has many bugs. Frankly speaking I am not sure about your requirement. But anyways try this :

map <string,int> VendorList;  
VendorList["abc"] = 1;
VendorList["mazda"] = 2;
VendorList["ford"] = 3;
VendorList["zoo"] = 4;
map <string,int>::iterator itr=VendorList.find("ford");
cout<<(itr->second);// this will print 3

EDIT :
Also as somebody has suggested to use vector of pairs,I think he is right. Try something like this.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
   typedef vector<pair<string,int> > Vm;
   Vm V;
   V.push_back(make_pair("abc",0));
   V.push_back(make_pair("mazda",111));
   V.push_back(make_pair("ford",222));
   V.push_back(make_pair("zoo",444));

   for(size_t i=0;i!=V.size();++i)
     if(V[i].first=="ford")
       cout<<(i+1);
}

Modify the above program as per requirement.
Hope that helps.

Prasoon Saurav