3

std :: mapの2つのインスタンスがある場合、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最初は、Non-static const memberの受け入れられた回答に記述されている次のエラーが発生したときのように、ベクトルをtypedefしようとしましたが、デフォルトの代入演算子を使用できません

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> >

4

1 に答える 1

2

これがあなたが探しているものかどうかはわかりません-ペアの最初のタイプから const を削除し、新しいペアタイプを返すメタ関数です。remove_const がどのように機能するかを知りたくない場合を除き、Boost が必要です。他の誰かがそれを手伝う必要があります。

#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; 
于 2012-01-05T19:45:04.630 に答える