开发者

Help with map C++

开发者 https://www.devze.com 2023-03-31 18:46 出处:网络
I have a map that links a size_t to a pair, of size开发者_运维知识库_t and int std::map< size_type, std::pair<size_t, unsigned int> > mapVals;

I have a map that links a size_t to a pair, of size开发者_运维知识库_t and int

std::map< size_type, std::pair<size_t, unsigned int> > mapVals;

essentially my understanding of this, is that maps work similar to stacks, and jst insert one after another, giving something similar to:

1 -> (2,2)
2 -> (4,7)
3 -> (8,5)
etc.

my question is, how do I obtain the value of the int. i.e. 2,7,5. I want to use this value as the max size of a while loop.


Maps are not similar to stacks; a stack maintains a first-in-last-out (FILO) strategy. A map is something that maps a key to a value.

If you do something like:

typedef std::pair<size_t,unsigned_int> my_pair;

// Insert elements
my_map[3] = my_pair(2,2);
my_map[9] = my_pair(4,7);
my_map[7] = my_pair(8,5);

You can retrieve the second element of your pair as:

my_map[9].second  // evaluates to 7


To access the int you can do one of two things

unsigned int myint = mymap[key].second;

where key is of type size_t. This works because using [size_t] on the map returns a std::pair<size_t, unsigned int> then calling .second on this gets you the uint.

You could also use iterators

std::map<size_t, std::pair<size_t, unsigned int> >::iterator itr = mymap.begin(); // say
unsigned int myint = itr->second.second;


typedef std::map< size_type, std::pair<size_t, unsigned int> > mymapT;
mymapT mapVals;

... // fill the map

first = mapVals[1].second;
second = mapVals[2].second;
third = mapVals[3].second;

... // do something useful


You can do something like this:

typedef std::map< size_type, std::pair<size_t, unsigned int> > myMap;
myMap mapVals;
// ... populate
myVals[1] = std::pair<size_t, unsigned int>(2,2);
// ...
for (myMap::const_iterator it = myVals.begin(); it != myVals.end(); ++it)
    unsigned int each_value = it->second.second;

The first it->second will give you the std::pair <size_t, unsigned int> element. The second second will give you the unsigned int contained in that pair.


I'm not sure what you want exactly

 for (std::map< size_type, std::pair<size_t, unsigned int> >::iterator it = mapVals.begin(); it != mapVals.end() ; it++)
     cout << it->second.first << " " << it->second.second << endl;
  • it->second : is the Value part of the map (in this case std::pair<size_t, unsigned int>)
  • it->second.second : is the second part of the pair (unsigned int)
0

精彩评论

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

关注公众号