使用 std::set_symmetric_difference 时,STL 容器的模板类型基于 std::map<>::value_type

Basing template type of STL container on std::map<>::value_type when using std::set_symmetric_difference

本文关键字:std map 类型 gt type value lt difference symmetric set STL      更新时间:2023-10-16

给定std::map的两个实例,我尝试使用std::set_set_symmetric_difference()算法来存储所有差异。我有以下工作代码:

#include <iostream>
#include <map>
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>
typedef std::map<std::string,bool> MyMap;
typedef std::vector< std::pair<MyMap::key_type,MyMap::mapped_type> > MyPairs;
//typedef std::vector< MyMap::value_type > MyPairs; 
using namespace std;
int main(int argc, char *argv[]) {
    MyMap previous;
    MyMap current;
    //Modified value
    previous["diff"] = true;
    current["diff"] = false;
    //Missing key in current
    previous["notInCurrent"] = true;
    //Missing key in previous
    current["notInPrevious"] = true;
    //Same value
    previous["same"] = true;
    current["same"] = true;
    cout << "All differences " << endl;
    MyPairs differences;
    std::back_insert_iterator<MyPairs> back_it(differences);
std::set_symmetric_difference(previous.begin(),previous.end(),current.begin(),current.end(),back_it);
    for(MyPairs::iterator it = differences.begin(); it != differences.end(); it++){
        cout << "(" << it->first << ":" << it->second << ") ";
    }
    cout << endl;
    return 0;
}

这打印出我所期望的:

All differences 
(diff:0) (diff:1) (notInCurrent:1) (notInPrevious:1)

让我头疼的是MyPairs的typedef,地图差异的向量。

最初,我试图将向量类型定义为typedef std::vector< MyMap::value_type > MyPairs,但出现了以下错误,该错误在非静态常量成员的可接受答案中有描述,can';t使用默认分配运算符

SetDifferenceMapVectorType.cpp:36:   instantiated from here
/usr/include/c++/4.2.1/bits/stl_pair.h:69: error: non-static const member 'const std::basic_string<char, std::char_traits<char>, std::allocator<char> > std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, bool>::first', can't use default assignment operator

这是因为映射中值的键是const,以避免更改键和使映射无效,这是有意义的。因为std::map<Key,Value>::value_typestd::pair<const Key, Value>,意味着operator=()不能用于向向量添加元素,这就是为什么在我的工作示例中不指定const的原因。

有没有更好的方法来定义MyPairs向量的模板参数,而不是冗余的?到目前为止,我能想到的最好的是std::vector< std::pair<MyMap::key_type, MyMap::mapped_type> >

我不确定这是否是您想要的——它是一个从对的第一个类型中删除常量并返回新对类型的元函数。Boost是必需的,除非你想深入了解remove_test是如何工作的——其他人必须在这方面提供帮助。

#include <boost/type_traits/remove_const.hpp>
template< typename PairType >
struct remove_const_from_pair
{
  typedef std::pair
    <
      typename boost::remove_const< typename PairType::first_type>::type,
      typename PairType::second_type
    > type;
};
typedef std::map<std::string,bool> MyMap;
//typedef std::vector< std::pair<MyMap::key_type,MyMap::mapped_type> > MyPairs;
typedef std::vector< remove_const_from_pair<MyMap::value_type>::type > MyPairs;