给定两个 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
我遇到以下错误一样,该错误在Non-static const member 的接受答案中描述,不能使用默认赋值运算符
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
意义不能用于向向量添加元素,这就是为什么在我的工作示例中不指定 const 的原因std::pair<const Key, Value>
。operator=()
有没有更好的方法来为 MyPairs 向量定义非冗余的模板参数?到目前为止我能想到的最好的就是std::vector< std::pair<MyMap::key_type, MyMap::mapped_type> >