在向量中查找特定字符串的最好方法是什么?
例如。 我有一些结构:
s_Some{
std::string lable;
s_some_junk some_junk;
};
和一个向量:
std::vector<s_Some> mSome;
然后我用很多 s_Somes 填充这个向量。
我需要为这个向量中的单个 s_Some 找到一个迭代器,它有一个特定的标签。 到目前为止,我只是遍历所有这些垃圾并将每个标签与想要的标签进行匹配。 这对我来说看起来有点愚蠢。 有更好的方法吗?
For instance. I have some structure:
s_Some{
std::string lable;
s_some_junk some_junk;
};
And a vector:
std::vector<s_Some> mSome;
And then I fill this vector with a lot of s_Somes.
I need to find an iterator for a single s_Some in this vector, which has a specific lable. So far I just iterate through all of this junk and match every lable with the one wanted. This looks a little bit stupid to me. Is there a better way to do so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
选项1)
如果您被迫使用 std::vector,但一旦向量被填充,它就保持不变,那么您可以对向量进行排序并使用二分搜索。 唯一的成本就是排序,并且不会有额外的开销。 搜索时间是对数O(logN)。
选项2)
如果您有自由并且可以选择不同的数据结构,请考虑使用映射(也是对数)或 unordered_map (预期 O(1),最差 O(n) )。
我刚刚注意到您说您希望将每个标签与正在查找的标签相匹配。 所以我的结论是你可以有重复的标签。 然后对于第 2 点,使用相应的 multi_map 容器,而对于第 1 点,事情会变得有点混乱。
Option 1)
If you are compelled to use the std::vector, but once the vector is filled it stays unchanged, then you could sort the vector and use the binary search. The only cost would be the sorting then and there will be no additional overhead. Searching time is logarithmic O(logN).
Option 2)
If you have the freedom and can choose different data structure, then consider using the map (also logarithmic) or unordered_map ( expected O(1), worst O(n) ).
I have just noticed that you said you wanted to match every label with the one being looked for. So I conclude you can have duplicate labels. Then for point 2 use corresponding multi_map containers, while for point 1 things get a bit messier.
如果您只搜索几次,或者每次搜索时您的向量可能有不同的内容,那么不幸的是没有其他选择; 你将不得不迭代整个向量。
但是,如果您的向量一旦创建就不会更改,并且您必须运行大量搜索,请执行以下操作:
这会快得多。
If you are to search only a few times or if your vector is likely to have different content every time you search, there's unfortunately no alternative; you will have to iterate through the whole vector.
If however your vector is not going to change once created and you have to run a large number of searches, do this:
This will be far quicker.
使用 a
并
通过 查找所需标签值的第一个实例 下
一个实例将通过递增迭代器找到。
参见 http://www.cppreference.com/wiki/stl/multimap/start
也就是说,除非您需要使用 std::vector。
Use a
and
Find the first instance of the value of lable you want by
The next instance will be found by incrementing the iterator.
cf. http://www.cppreference.com/wiki/stl/multimap/start
That is, unless you're required to use a std::vector.
您还可以使用 地图 www.cppreference.com/wiki/stl/list/start" rel="nofollow noreferrer">列表
You could also use a Map of Lists
您可以使用 find_if 算法来执行此操作。 定义一个像这样的谓词:
在搜索时你可以使用
You can find_if algorithm to do this. Define a predicate some thing like this:
And while searching you can use