带有std :: vector 的快速搜索算法

问题描述 投票:10回答:3
for (std::vector<const std::string>::const_iterator it = serverList.begin(); it != serverList.end(); it++) { // found a match, store the location if (index == *it) // index is a string { indexResult.push_back(std::distance(serverList.begin(), it)); // std::vector<unsigned int> } }
我已经编写了上面的代码,以查看字符串的向量,并返回具有任何“匹配”位置的另一个向量。

有没有一种方法可以做,但是更快? (如果我的容器中有10,000件物品,则需要一段时间)。请注意,我必须检查所有项目是否匹配,并将其位置存储在容器中。

Bonus Kudos:​​任何人都知道我如何进行搜索,从而找到部分结果的任何方式/链接(例如:搜索“ coolro”并在变量“ coolroomhere”中存储位置]

for(std :: vector

:: const_iterator it = serverList.begin(); it!= serverList.end(); it ++){//找到匹配项,如果(index == * it)则存储位置//索引...

c++ search vector
3个回答
7
投票
基本上,您是在询问是否可以检查所有元素匹配,而不检查所有元素。如果有某种外部元信息(例如对数据进行排序),则有可能(例如使用二进制搜索)。否则,就其本质而言,要检查所有元素,您必须检查所有元素。

10
投票
对向量排序后使用binary_search

2
投票
如果将容器设置为std::map而不是std::vector,则所使用的基础数据结构将是经过优化的结构,可进行类似这样的关键字搜索。
© www.soinside.com 2019 - 2024. All rights reserved.