迭代器操作的问题
我有一个 std::map,我正在使用迭代器来查找某个键、值对。找到它后,我无法从迭代器获取键值对的位置。通过进行另一个查找,我可以得到它,但我想要解决这个问题。
//mycode is this
std::map<std::string,myclass*> mymap;
size_t myfind(const std::string &s)
{
std::map<std:string,myclass*>::iterator i=mymap.find(s);
if((i==mymap.end())||((*i).second==0))
{
std::cout<<"some error\n";
}
else
{
//here i need to return the size_t value of the iterator i
}
}
注意:将 size_t 编辑为键值对的位置
i have a std::map and i am using iterator to find a certain key,value pair. After finding it i am unable to get the position of the key,value pair from the iterator. By doing another find i can get it, but i want a work around for this.
//mycode is this
std::map<std::string,myclass*> mymap;
size_t myfind(const std::string &s)
{
std::map<std:string,myclass*>::iterator i=mymap.find(s);
if((i==mymap.end())||((*i).second==0))
{
std::cout<<"some error\n";
}
else
{
//here i need to return the size_t value of the iterator i
}
}
NOTE: edited size_t as the position of key,value pair
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想返回结果的“位置”:
但是,您最好只返回迭代器!
If you want to return the "position" of the result:
However, you are probably better off just returning the iterator!
size_t
与什么有什么关系?你找到了键值对,键是一个字符串,值是指向某个类的指针。就是这样。您想要什么size_t
值?让您走上正轨的一些背景知识:STL 中的映射和集合通常实现为平衡二叉树(红黑树)。树中的每个节点都有值(对于集合来说只是键,或者对于映射来说是对)和两个指向子节点的指针。您可以将
map::iterator
视为指向具有奇特重载运算符的节点的指针,因此,递增迭代器值会将指针按排序顺序移动到下一个节点。所以不存在“迭代器的size_t
值”。它是包装指向二叉树节点的指针的类的实例。What does
size_t
have to do with anything? You found the key-value pair, key is a string, value is a pointer to some class. That's it. Whatsize_t
value did you have in mind?Some background to put you onto right track: map and set in STL are usually implemented as balanced binary tree (red-black tree.) Each node in the tree has the value (just key for set, or pair for map,) and two of pointers to child nodes. You can think of
map::iterator
as a pointer to a node with fancy overloaded operators so, say, incrementing the iterator value moves the pointer to the next node in sort order. So there's no "size_t
value of the iterator". It's an instance of a class that wraps a pointer to binary tree node.