热查找<string>矢量<string>中的矢量元素
Hot to find vector<string> element in a vector<string>
我有一些vector<string> v1
,使用push_back填充:
v1.push_back("a");
v1.push_back("b");
v1.push_back("c");
v1.push_back("d");
v1.push_back("e");
我有另一个vector<string> v2
和一个迭代器,它包含某个元素
vector<string>::iterator v2iter;//some element of v2
我需要检查v1中是否有v2iter元素
find(v1, v2iter); //smth like this
可以使用标准算法std::find
#include <algorithm>
#include <vector>
//..
if ( std::find( v1.begin(), v1.end(), *v2iter ) != v1.end() )
{
std::cout << *v2iter << " is found in v1" << std::endl;
}
或者可以使用标准算法std::any_of
#include <algorithm>
#include <vector>
#include <functional>
//..
if ( std::any_of( v1.begin(), v1.end(), std::bind2nd( std::equal_to<std::string>(), *v2iter ) ) )
{
std::cout << *v2iter << " is found in v1" << std::endl;
}
或者如果第一个向量是有序的那么你可以使用算法std::binary_search
#include <algorithm>
#include <vector>
//..
if ( std::binary_search( v1.begin(), v1.end(), *v2iter ) )
{
std::cout << *v2iter << " is found in v1" << std::endl;
}
您可以使用:
vector <string > :: iterator it , fit ;
for ( it = v2.begin() ; it != v2.end() ; it++ ){
fit = find ( v1.begin() , v1.end() , *it ) ;
if ( fit != v1.end() ){
// means that the element is present in v1
}
}
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- EASTL矢量<向量<int>>连续的
- 使用 std::string () const 函数启动线程或未来
- 使用char类型将decimal转换为string,将string转换为decimal
- 迭代和比较映射<字符串、矢量<string>> c++ 中的值
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 将向量解析<string>为字符串
- 'string.assign(string.data(), 5)' 是明确定义的还是 UB?
- 如何更改大小(std::string)
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- std::string 的对象真的可以移动吗?
- 与'operator='不匹配(操作数类型'String'且"void")
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- <string> 使用 for 循环写入向量