开发者

the value of iterator

开发者 https://www.devze.com 2022-12-14 17:59 出处:网络
i created a map. i want to print the index of the key to a file开发者_开发百科 using the itr in the map.

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)


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.


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();


As such, the concept of 'index' doesn't really fit with Maps.

Maps are just key-value pairs where you store a value (say, '111') and access it using a key (say 'mazda'). In this way you don't really need an index in order to access '111', you can just use the key 'mazda'.

If you do want your application to be index based however, consider using a different data structure like a Vector or a Linked List.

0

精彩评论

暂无评论...
验证码 换一张
取 消