C++ 检查字符串是否作为向量中的元素存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5489729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:16:10  来源:igfitidea点击:

Checking if a string is present as an element in a vector

c++vector

提问by user620189

What's the most efficient way to check whether an stl vector of strings contains a specific string?

检查字符串的 stl 向量是否包含特定字符串的最有效方法是什么?

回答by Mark B

The obvious yet possibly too-slow solution is std::find(vec.begin(), vec.end(), your_string);

明显但可能太慢的解决方案是 std::find(vec.begin(), vec.end(), your_string);

If your vector isn't changing much, sort it first, then use binary_search, lower_bound, upper_bound, or equal_range. If your vector changes a lot, consider using a set/multiset(or if needed map/multimap) instead.

如果您的载体没有太大变化,但排序第一,然后使用binary_searchlower_boundupper_bound,或equal_range。如果您的向量变化很大,请考虑使用set/ multiset(或如果需要map/ multimap)。

Depending on your needs a hash (unordered_set) might be appropriate as well, but it's more different from your initial container choice than normal ordered containers, and not supplied prior to C++0x (you can get it from boost easily).

根据您的需要,散列 ( unordered_set) 也可能是合适的,但它与您的初始容器选择比普通有序容器更不同,并且在 C++0x 之前不提供(您可以轻松地从 boost 获得它)。

回答by quamrana

Use std::findto find the target string. This is a linear search, so beware searching large vectors.

使用std::find找到目标字符串。这是一个线性搜索,所以要小心搜索大向量。

To find out if the vector contains the target or not, use:

要确定向量是否包含目标,请使用:

bool isPresent = (std::find(vec.begin(), vec.end(), target) != vec.end());

回答by davidhigh

Here is a C++11 alternative:

这是一个 C++11 替代方案:

#include<functional>
#include<vector>
#include<string>

std::vector<std::string> v;
bool elementFound = std::any_of(v.begin(), v.end(), [](std::string const& s) {return s=="string-to-search";});

Feel free to adjust the lambda function to what you want, e.g.

随意将 lambda 函数调整为您想要的,例如

[](std::string const& s) {return s.size()>3;}

回答by jmccarthy

vector<string> v;
vector<string>::iterator it;
it = std::find(v.begin(), v.end(), "stringToFind");

回答by Mahesh

Use std::find to find the string.

使用 std::find 查找字符串。

std::find(stringVector.begin(), stringVector.end(), "specificStringToFind") ;