问题
i have two maps and i need to find the differences and create a new map that only has the differences. Not sure how to do this. I tried using set_difference but don't really understand how it works. Any help would be appreciated. thanks
// header file
typedef std::map<std::string, int> MapCol;
typedef std::map<std::string, MapCol> MapRow;
MapRow m_mapRows;
//.cpp fle
CheckForDifferences( const Table& rhs )
{
Table diffTable;
vector<string> v;
vector<string>::iterator it;
it=set_difference (m_mapRows.begin(), m_mapRows.end(), diffTable.m_mapRows.begin(), diffTable.m_mapRows.end, v.begin());
}
edit:
std::set_difference( m_mapRows.begin(), m_mapRows.end(),
rhs.m_mapRows.begin(), rhs.m_mapRows.end(), diffTable.m_mapRows.begin());
ok this is what i tried, but i get errors, the first one being error C2678: binary '=' : no operator found which takes a left-hand operand of type 'const std::string' (or there is no acceptable conversion)
any ideas?
回答1:
If you have two sorted containers a
and b
and you want to copy the set of objects that aren't in either one into another container c
, you'd do this:
std::set_symmetric_difference(
a.begin(), a.end(),
b.begin(), b.end(),
std::back_inserter(c) );
If you just want the elements from a
that aren't in b
, use set_difference
instead of set_symmetric_difference
.
回答2:
In your code
std::set_difference( m_mapRows.begin(), m_mapRows.end(),
rhs.m_mapRows.begin(), rhs.m_mapRows.end(), diffTable.m_mapRows.begin());
you try to use regular iterator as output, that does not work. In your case you can use std::inserter
std::set_difference( m_mapRows.begin(), m_mapRows.end(),
rhs.m_mapRows.begin(), rhs.m_mapRows.end(), std::inserter( diffTable.m_mapRows, diffTable.m_mapRows.begin()));
回答3:
This is my take on it. Very basic. You start off from a copy of the left hand operand and remove all that is present in the right hand operand. It leaves you with the difference as defined by set theory.
template< class TMap >
auto MapDiff( const TMap & lh, const TMap & rh )
{
auto result = lh ;
for( auto const & item : rh )
{
result.erase( item.first ) ;
}
return result ;
}
来源:https://stackoverflow.com/questions/13201463/how-i-can-return-a-stdmap-containing-the-differences-of-two-maps-in-c