在结构的向量中找到
find in vector of struct
我有一个结构和两个类似的向量
struct CodeColor
{
int index;
string color;
};
std::vector<CodeColor> secret_code;
std::vector<CodeColor> my_code;
我需要在secret_code
的my_code
中搜索每个项目。我需要得到的是,对于my_code
中的每个项目
secret_code
中是否存在与index
和color
都匹配的项- 如果没有,是否有只匹配
color
的项目 - 以上两种都没有
事实上,我可以通过两个for循环来实现这一点,但我不喜欢这样做(考虑到时间复杂性)。我正在尝试使用find_if
或任何其他方式。有什么建议吗?
您可以编写一个与此示例中的函数类似的函数Vector secret_code只查看一次。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
struct CodeColor
{
int index;
std::string color;
};
enum class SEARCH_RESULT { NO_MATCH, PARTIAL_MATCH, EXACT_MATCH };
SEARCH_RESULT find( const std::vector<CodeColor> &v, const CodeColor &value )
{
SEARCH_RESULT result = SEARCH_RESULT::NO_MATCH;
auto it = std::find_if( v.begin(), v.end(),
[&value]( const CodeColor &c )
{
return ( c.color == value.color );
} );
if ( it != v.end() )
{
result = SEARCH_RESULT::PARTIAL_MATCH;
it = std::find_if( it, v.end(),
[&value]( const CodeColor &c )
{
return ( c.index == value.index &&
c.color == value.color );
} );
if ( it != v.end() ) result = SEARCH_RESULT::EXACT_MATCH;
}
return result;
}
int main()
{
std::vector<CodeColor> secret_code =
{
{ 1, "Red" }, { 2, "Green" }, { 3, "Blue" }
};
std::vector<CodeColor> my_code =
{
{ 2, "Green" }, { 1, "Blue" }
};
for ( const CodeColor &c : my_code )
{
std::cout << static_cast<int>( find( secret_code, c ) ) << ' ';
}
std::cout << std::endl;
return 0;
}
输出为
2 1
您可以重写函数,使其返回一对枚举器和相应的迭代器。
您可以使用这种方法:
#include <algorithm>
#include <set>
set<CodeColor> intersect;
set_intersection(secret_code.begin(),secret_code.end(),my_code.begin(),my_code.end(), // sorted!
std::inserter(intersect,intersect.begin()));
在这种方法中,
template< class InputIt1, class InputIt2, class OutputIt >
OutputIt set_intersection( InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,
OutputIt d_first );
构造一个从d_first开始的排序范围,该范围由在两个排序范围[first1,last1)和[first2,last2)中找到的元素组成;因此,您需要为CodeColor
重载< operator
相关文章:
- 将结构向量排序为子组
- 访问存储在向量C++中的结构的多态成员
- NLOHMANN 的 JSON 库将数组转换为结构向量
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 如何在 c++ 中创建结构向量的映射
- 带unique_ptr的结构向量
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 将 int 映射到 C++ 中的向量结构
- 如何在 c++ 中的向量结构中使用结构向量
- 无法将值存储到向量结构中
- 无法将.CSV文件读取为代表向量结构的类
- MPI,C,派生类型,向量结构
- 向量结构的打印成员
- 在 c++ 中对向量<结构 S> 进行二分搜索?
- 不需要删除向量<结构A*>
- 在C++中循环向量结构<string>
- 将字符串放入字符串的向量结构中
- 共享内存中的向量结构
- 我的向量结构没有像预期的那样迭代