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_type
にstd::pair<const Key, Value>
意味operator=()
を使用できないためです。これが、私の作業例でconstを指定しない理由です。
冗長ではないMyPairsベクトルのテンプレートパラメーターを定義するためのより良い方法はありますか?私がこれまでに思いついた最高のものはstd::vector< std::pair<MyMap::key_type, MyMap::mapped_type> >