紧急求教:怎么根据map中元素的序号取得map的键?

jay314159 2011-01-07 09:59:29
比如
map<int,string> testMap;
int index = 0;
cout<<testMap[index];

那么
testMap[index]就会返回第一个元素的string值。
现在的问题是,有没有什么办法能够根据index取得map的键?
不要迭代器的方法。
...全文
779 12 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
skinnymonkey 2011-01-09
  • 打赏
  • 举报
回复
什么叫根据index取map的键,这里的index就是键。
taodm 2011-01-09
  • 打赏
  • 举报
回复
那就不要用map
jay314159 2011-01-09
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 skinnymonkey 的回复:]
什么叫根据index取map的键,这里的index就是键。
[/Quote]

题目描述不当,
其实应该说,假如我要取map的第i个键值对(pair),应该怎么做。
jay314159 2011-01-09
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 dizuo 的回复:]
有没有什么办法能够根据index取得map的键?
==================
可以通过map::find函数获得index值。

C/C++ code

// map::find
#include <iostream>
#include <map>
using namespace std;

int main ()
{
map<char,int> mymap……
[/Quote]

谢谢!
find_if也可以,
不过效率比较慢。
jay314159 2011-01-09
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 h100037 的回复:]
map<int,string>::iterator it = testMap.begin() + index;
这样或许能得到你要的第index键值对
[/Quote]

似乎map的迭代器不能用+操作符,只能用++
h100037 2011-01-08
  • 打赏
  • 举报
回复
map<int,string>::iterator it = testMap.begin() + index;
这样或许能得到你要的第index键值对
ryfdizuo 2011-01-08
  • 打赏
  • 举报
回复
有没有什么办法能够根据index取得map的键?
==================
可以通过map::find函数获得index值。

// map::find
#include <iostream>
#include <map>
using namespace std;

int main ()
{
map<char,int> mymap;
map<char,int>::iterator it;

mymap['a']=50;
mymap['b']=100;
mymap['c']=150;
mymap['d']=200;

it=mymap.find('b');
mymap.erase (it);
mymap.erase (mymap.find('d'));

// print content:
cout << "elements in mymap:" << endl;
cout << "a => " << mymap.find('a')->second << endl;
cout << "c => " << mymap.find('c')->second << endl;

return 0;
}

Arcticanimal 2011-01-07
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 pluminsnow 的回复:]

你的index就是键值,你对map的用法没弄清楚,仔细看看资料
你的代码如果要合法的话,还要加上一句


C/C++ code

map<int,string> testMap;
int index = 0;
testMap[index] = "abc";//,这句相当于insert一个元素到map里,
//不加这句程序直接挂掉,因为……
[/Quote]

其实不会挂掉的,可以试一试,使用下标运算符访问时键值不存在map自动插入该键值
noock 2011-01-07
  • 打赏
  • 举报
回复
其实你想根据顺序来取MAP的元素的想法就是不太正确的,因为MAP内部是树形结构,而且各元素的位置是动态变化的,根据插入的元素的键进行排序,所以通过下标这种方法来取MAP的元素是没有任何意义的
你可能需要重新考虑你的数据结构了,想用下标存取就可以考虑vector了
jay314159 2011-01-07
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 pluminsnow 的回复:]
你的index就是键值,你对map的用法没弄清楚,仔细看看资料
你的代码如果要合法的话,还要加上一句



C/C++ code

map<int,string> testMap;
int index = 0;
testMap[index] = "abc";//,这句相当于insert一个元素到map里,
//不加这句程序直接……
[/Quote]

对 我理解错了,
那么有没有办法可以直接得到map的第i个键值对呢?
  • 打赏
  • 举报
回复
知道红黑树吗?map原理就是红黑树
pluminsnow 2011-01-07
  • 打赏
  • 举报
回复
你的index就是键值,你对map的用法没弄清楚,仔细看看资料
你的代码如果要合法的话,还要加上一句



map<int,string> testMap;
int index = 0;
testMap[index] = "abc";//,这句相当于insert一个元素到map里,
//不加这句程序直接挂掉,因为你的map是空的
cout<<testMap[index];


65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧