給出std :: map的兩個實例我試圖使用std :: set_set_symmetric_difference()算法來存儲所有差異。我有以下工作代碼:使用std :: set_symmetric_difference時在std :: map上使用STL容器的模板類型
#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 std::vector<MyMap::value_type> MyPairs
我降落了與在的Non-static const member, can't use default assignment operator
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
接受的答案中描述的下列誤差的typedef載體這是因爲在地圖的值的鍵是常量以避免更改密鑰並使地圖失效,這是合理的。因爲std::map<Key,Value>::value_type
是std::pair<const Key, Value>
含義operator=()
不能用於添加元素到向量,這就是爲什麼不指定const作品在我的工作示例。
有沒有更好的方法來定義MyPairs向量的模板參數是不是多餘的?到目前爲止我所能得到的最好的結果是std::vector< std::pair<MyMap::key_type, MyMap::mapped_type> >
這是一個更大的問題的一部分?如果是這樣,可能有一個解決方案,我們可以提供幫助 - 但就目前來看,我不認爲有任何方法可以更通用地添加大量代碼。 – Zac 2012-01-05 19:34:14