【发布时间】:2013-02-17 08:30:43
【问题描述】:
这是我的迭代器位置代码
struct node {
int nodeid;
vector<fingerTable> fTable;
vector<string> data;
};
vector<node> cNode;
vector<node>::iterator position = find(cNode.begin(),cNode.end(), id);
我有大约 100 个对象,我正在尝试查找例如 nodeid "80" 的索引/元素/位置,假设我的对象全部按 nodeid 升序排序。
我关心的是速度和内存使用,我以前使用过
for(int i=0;i<cNode.size();i++)
{
//if logic-- match nodeid with the nodeid input.. then assign the i to an integer..
}
但现在我正在尝试使用和迭代器,我听说它更快.. 任何关于修复它的建议,或者是否有更好的方法通过其值“nodeid”找到我的向量索引
我知道 map 对于我的情况来说是一个很好的标准容器,但我有点没时间做这些更改,所以我必须坚持使用向量。..
vector<node>::iterator position = find(cNode.begin(),cNode.end(), id);
当我尝试编译上面的迭代器行时输出错误。
In member function ‘void chord::removePeer(int)’:
testfile.cpp:532:69: error: no matching function for call to ‘chord::find(std::vector<chord::node>::iterator, std::vector<chord::node>::iterator, int&)’
testfile.cpp:532:69: note: candidate is:
testfile.cpp:177:5: note: int chord::find(int, int, bool)
testfile.cpp:177:5: note: no known conversion for argument 1 from ‘std::vector<chord::node>::iterator {aka __gnu_cxx::__normal_iterator<chord::node*, std::vector<chord::node> >}’ to ‘int’
【问题讨论】:
-
您是否包含了? id 的类型是什么?
-
@billz 我确实包含了
,id 是一个整数,它是唯一的,不同的,并且只在整个向量中出现一次。它按升序排序 -
这个问题看起来很像 11 小时前的How can I get vector's index by its data in C++?,而I replied "
std::find()runs in linear time (O(n)), the same as yourfor-loop."。如果您想在亚线性时间内运行,请使用std::lower_bound()。
标签: c++