Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/124.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何访问地图的第i个成员?_C++ - Fatal编程技术网

C++ 如何访问地图的第i个成员?

C++ 如何访问地图的第i个成员?,c++,C++,我想访问c++中map的任何成员。 比如,如果我有一个map={(4,3)、(5,6)、(9,8)} 说我想得到这张地图的第二个成员。我试过了 map<int, int>::iterator it = mpp.begin(); cout << (it+1)->first << " " << (it+1)->second << endl; map::iterator it=mpp.begin(); 首先,我采用了一种简单的

我想访问
c++
map
的任何成员。 比如,如果我有一个
map={(4,3)、(5,6)、(9,8)}

说我想得到这张地图的第二个成员。我试过了

map<int, int>::iterator it = mpp.begin();
cout << (it+1)->first << " " << (it+1)->second << endl;
map::iterator it=mpp.begin();

首先,我采用了一种简单的方法。 假设我必须从乞讨者那里获得第j个元素

map<int, int>::iterator it = mpp.begin();
while(j--)
          it++;
cout << it->first << " " << it -> second << endl;
map::iterator it=mpp.begin();
而(j--)
it++;

cout first只有随机访问迭代器对
操作符+
操作符-
具有重载。双向迭代器,如
std::map::iterator
不支持。但是,可以通过使用
std::next
(从C++11开始)线性地推进它们,这将

返回迭代器的第n个后续项

或者
std::advance

将给定的迭代器递增n个元素


请注意,查找
std::map
的第n个元素的复杂性具有线性复杂性。还有其他类似的数据结构提供了
std::map
所具有的特性,但也允许更快的第n个成员查找。所以,另一种数据结构可能更适合您的用例

例如,二叉搜索树可以用每个子树的大小来扩充。这种结构称为顺序统计树。对于内存开销的小线性增加,它为查找第n个元素提供了O(logn)复杂性。

请看。