如何在c++中仅针对键的子集有效地比较两个字符串映射

How to efficiently compare two maps of strings in C++ only for a subset of the keys

本文关键字:比较 有效地 映射 字符串 两个 子集 c++      更新时间:2023-10-16

我想知道是否只有通过应用一些标准算法才能编写一个简短的函数,该函数比较两个std::map<string, string>并返回true,如果所有键值(但有些)对都为真。

例如,这两个映射应该计算为等于
map<string,string> m1, m2;
m1["A"]="1";
m2["A"]="1";
m1["B"]="2";
m2["B"]="2";
m1["X"]="30";
m2["X"]="340";
m1["Y"]="53";
m2["Y"]="0";

假设两个映射具有相同的大小,并且它们的所有元素都必须进行两两比较,除了键"x"存储的值;和键"y"。第一次尝试将是一个非常低效的双嵌套for循环。

我相信会有更好的解决办法的。

我不知道你到底在找什么,所以让我先给出完全相等,然后是键相等。也许后者已经符合你的需要了。

<标题>完全平等h1> em>(虽然可以使用std::map自己的比较操作符来测试标准等价,但以下操作符可以用作基于每个值的比较的基础。)

可以用std::equalstd::operator==来检验std::pair s的完全相等性:

#include <utility>
#include <algorithm>
#include <string>
#include <iostream>
#include <map>
template <typename Map>
bool map_compare (Map const &lhs, Map const &rhs) {
    // No predicate needed because there is operator== for pairs already.
    return lhs.size() == rhs.size()
        && std::equal(lhs.begin(), lhs.end(),
                      rhs.begin());
}
int main () {
    using namespace std;
    map<string,string> a, b;
    a["Foo"] = "0";
    a["Bar"] = "1";
    a["Frob"] = "2";
    b["Foo"] = "0";
    b["Bar"] = "1";
    b["Frob"] = "2";
    cout << "a == b? " << map_compare (a,b) << " (should be 1)n";
    b["Foo"] = "1";
    cout << "a == b? " << map_compare (a,b) << " (should be 0)n";
    map<string,string> c;
    cout << "a == c? " << map_compare (a,c)  << " (should be 0)n";
}
<标题>键平等h1> C + + 2003 根据上面的代码,我们可以向std::equal调用添加一个谓词:
struct Pair_First_Equal {
    template <typename Pair>
    bool operator() (Pair const &lhs, Pair const &rhs) const {
        return lhs.first == rhs.first;
    }
};
template <typename Map>
bool key_compare (Map const &lhs, Map const &rhs) {
    return lhs.size() == rhs.size()
        && std::equal(lhs.begin(), lhs.end(),
                      rhs.begin(),
                      Pair_First_Equal()); // predicate instance
}
int main () {
    using namespace std;
    map<string,string> a, b;
    a["Foo"] = "0";
    a["Bar"] = "1";
    a["Frob"] = "2";
    b["Foo"] = "0";
    b["Bar"] = "1";
    b["Frob"] = "2";
    cout << "a == b? " << key_compare (a,b) << " (should be 1)n";
    b["Foo"] = "1";
    cout << "a == b? " << key_compare (a,b) << " (should be 1)n";
    map<string,string> c;
    cout << "a == c? " << key_compare (a,c)  << " (should be 0)n";
}

c++ (C + + 11)

使用新的lambda表达式,可以这样做:

template <typename Map>
bool key_compare (Map const &lhs, Map const &rhs) {
    auto pred = [] (decltype(*lhs.begin()) a, decltype(a) b)
                   { return a.first == b.first; };
    return lhs.size() == rhs.size()
        && std::equal(lhs.begin(), lhs.end(), rhs.begin(), pred);
}

c++ (C + + 14)

<一口>添加2014-03-12

使用新的泛型lambda表达式,您可以这样做:

template <typename Map>
bool key_compare (Map const &lhs, Map const &rhs) {
    auto pred = [] (auto a, auto b)
                   { return a.first == b.first; };
    return lhs.size() == rhs.size()
        && std::equal(lhs.begin(), lhs.end(), rhs.begin(), pred);
}

作为一个样式问题,您还可以将c++ 11和c++ 14中的lambda表达式直接内联为参数:

bool key_compare (Map const &lhs, Map const &rhs) {
    return lhs.size() == rhs.size()
        && std::equal(lhs.begin(), lhs.end(), rhs.begin(), 
                      [] (auto a, auto b) { return a.first == b.first; });
}

答案很简单,我们可以通过等价关系运算符("==")直接比较两个映射,就像比较两个变量一样。

#include<bits/stdc++.h>
using namespace std;
int main()
{
map<string,int> m1;
map<string,int> m2;
m1["str1"]=47;
m1["str2"]=87;
m2["str1"]=47;
m2["str2"]=87;
if(m1==m2)
cout<<"maps are equal"<<endl;
else
cout<<"maps are not equal"<<endl;   
}

输出:https://i.stack.imgur.com/MCmN4.png

如果你想同时访问两个大小相等的map,那么你应该创建迭代器,并以这种方式遍历两个map。

 map<char, int> :: iterator itr1, itr2;
 itr1=first.begin();
 itr2=last.begin();
 
 while(itr1!=first.end() && itr2!=last.end())
 {
     if(itr1->first!=itr2->first || itr1->second!=itr2->second)
     {
       cout<<"Error"<<endl;
     }
     else 
     {
       cout<<"Ok so far"<<endl;
     }
     itr1++;
     itr2++;
 }