在结构的向量中找到

find in vector of struct

本文关键字:向量 结构      更新时间:2023-10-16

我有一个结构和两个类似的向量

struct CodeColor
{
 int index;
 string color;
};

std::vector<CodeColor> secret_code;
std::vector<CodeColor> my_code;

我需要在secret_codemy_code中搜索每个项目。我需要得到的是,对于my_code 中的每个项目

  1. secret_code中是否存在与indexcolor都匹配的项
  2. 如果没有,是否有只匹配color的项目
  3. 以上两种都没有

事实上,我可以通过两个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