[英]Is there a way to get a specific key-value pair from the map?
I am currently learning about maps in STL. 我目前正在学习有关STL中的地图的信息。 I want to know how to get a specific key value pair from the map.
我想知道如何从地图上获取特定的键值对。 For example, 3rd key-value pair from the map below.
例如,下面地图中的第三个键值对。
'C'-> 1
'A'-> 1
'B'-> 1
'C'-> 1
'D'-> 1
'E'-> 2
Yes, we can access "The third key-value pair" of a map, but it's not very straightforward. 是的,我们可以访问地图的“第三个键值对”,但这不是很简单。 We need to get an iterator the beginning of the map and then advance it twice (note, that in more generic code you should check that the map has the appropriate size before doing something like this)
我们需要在地图的开头获得一个迭代器,然后将其前进两次(请注意,在更通用的代码中,您应先检查地图是否具有适当的大小,然后再执行类似的操作)
std::map<char, int> my_map;
my_map['C'] = 3;
my_map['A'] = 1;
my_map['B'] = 2;
auto begin = my_map.begin();
std::advance(begin, 2);
std::cout << begin->first << " : " << begin->second << std::endl;
Output: 输出:
C : 3
C:3
Note that the 3rd element is actually the first key-value pair we inserted. 请注意,第3个元素实际上是我们插入的第一个键值对。 This is because keys are inserted in sorted order.
这是因为键是按排序顺序插入的。
If I have understood you correctly you need something like 如果我对您的理解正确,则需要类似
#include <iostream>
#include <map>
#include <iterator>
int main()
{
std::map<char, unsigned int> m =
{
{ 'A', 1 }, { 'B', 1 }, { 'C', 1 }, { 'D', 1 }, { 'E', 2 }
};
auto it = std::next( std::begin( m ), std::min<decltype( m )::size_type>( m.size(), 2 ) );
if ( it != std::end( m ) )
{
std::cout << it->first << ": " << it->second << '\n';
}
return 0;
}
The program output is 程序输出为
C: 1
That is you can use operations with iterators. 也就是说,您可以将操作与迭代器一起使用。
Or maybe you need to use just the method find
of the class as for example 或者也许您只需要使用类的方法
find
,例如
#include <iostream>
#include <map>
#include <iterator>
int main()
{
std::map<char, unsigned int> m =
{
{ 'A', 1 }, { 'B', 1 }, { 'C', 1 }, { 'D', 1 }, { 'E', 2 }
};
auto it = m.find( 'C' );
if ( it != std::end( m ) )
{
std::cout << it->first << ": " << it->second << '\n';
}
return 0;
}
Again the program output is 程序输出再次是
C: 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.