2012-02-01 52 views

回答

5

我以为你不想要搜索整个集合:只使用std::set<std::string>::lower_bound()和迭代,直到你找到一个std::string不具有所期望的前缀:

std::string const prefix("bab"); 
for (std::set<std::string>::const_iterator it(setStrings.lower_bound(prefix)); 
    it != setStrings.end() && it->find(prefix) == 0; ++it) { 
    std::cout << "prefixed: '" << *it << "'\n"; 
} 

如果您只是想找到是否有一个字符串与相应的前缀,你可以使用条件在循环中。

+0

+1的答案优于O(N)复杂性。为什么任何人都会用'std :: set <>进行线性搜索......超出了我的范围...... – ildjarn 2012-02-01 23:22:48

+0

查找带有前缀的所有字符串的复杂度仍然具有相同的复杂度O(N):最糟糕的情况是所有字符串都有这个前缀。但是,它确实是一个O(log N)算法,用于找到带有前缀的第一个字符串。 – 2012-02-02 00:00:48

+0

正确的,问题是“*是存储的字符串的前缀之一*”,所以我将其作为查找单个元素(以及在此情况下代码中需要的所有内容都是“中断”)。 – ildjarn 2012-02-02 00:03:43

1

如何做到这一点还有更多的方法。这就是其中之一:

std::set<std::string> setStrings; 

setStrings.insert("abc"); 
setStrings.insert("abcd"); 
setStrings.insert("babc"); 

std::string prefix("bab"); 

std::set<std::string>::iterator i; 
for (i = setStrings.begin(); i != setStrings.end(); ++i) 
{ 
    if ((*i).compare(0, prefix.length(), prefix) == 0) 
     std::cout << *i << " starts with: " << prefix << std::endl; 
} 

这是另一种方式:

std::set<std::string>::iterator i; 
for (i = setStrings.begin(); i != setStrings.end(); ++i) 
{ 
    if ((*i).substr(0, prefix.length()) == prefix) 
     std::cout << *i << " starts with: " << prefix << std::endl; 
} 
+1

鉴于'std :: set'已排序,您可以在一般情况下更高效地执行此操作。 – Managu 2012-02-01 23:22:08

+0

的确如此。说实话,我在写这个答案时并没有考虑效率。 – LihO 2012-02-01 23:33:21

0
std::set<std::string> setString; 
    setString.insert("abc"); 
    setString.insert("abcd"); 
    setString.insert("babc"); 
    for (auto &i : setString){ 
     std::cout << i << " result: "<< (i.find("bab")==0) <<std::endl; 
    } 

这是C++ 11,但str::find以同样的方式在老年人C++

abc result: 0 
abcd result: 0 
babc result: 1