views:

341

answers:

3

How to convert a multimap<int,int> to vector<pair<int,int> > efficiently

EDIT: Sorry for the trouble I was actually looking for converting vector to map

+1  A: 

I believe that the naive approach is also the most efficient one: iterate over the multimap, and add each element to the vector. As an optimization, you should v.reserve(m.size) before you start.

The elements are typically stored in a tree in the multimap, in objects spread over the heap. For the vector, they must be in contiguous memory: this requires that you really have to copy them together.

Martin v. Löwis
ok then is it possible to do with for_each ?
yesraaj
No need: vector::assign(Iter begin, Iter end) is a single operation that takes care of both the memory allcoation and the loop.
MSalters
+4  A: 

The value type of a multimap<int,int> is pair<int,int> - exactly what you would like your vector to hold. So, you can use the constructor to initialize the vector from the multimap:

std::vector< std::pair<int,int> > v( mmap.begin(), mmap.end() );

Or, if you have an existing vector where you want to copy the elements:

v.resize( mmap.size() );
std::copy( mmap.begin(), mmap.end(), v.begin() );

You can also use the std::back_inserter, but that would be slower in general due to vector reallocations:

std::copy( mmap.begin(), mmap.end(), std::back_inserter(v) );

EDIT To answer your other question - you can convert a vector to a multimap in a similar way. The multimap also has a constructor which accepts an iterator range:

std::multimap<int,int> mmap(v.begin(), v.end());

This, of course, assumes that v is std::vector< std::pair<int,int> >.

Bojan Resnik
The value type of associative containers in C++ has a constant key. That is: std::multimap<Key,Value>::value_type is std::pair< const Key, Value>. The reason is that if the Key was not constant, it could be changed through non-const iterators breaking the container invariants (the element would be in a wrong position after the key update)
David Rodríguez - dribeas
A: 

I am trying to find duplicates in a multimap consisting of vectors of structs.

multimap::iterator,vector::iterator> mymm;

multimap::iterator,vector::iterator>::iterator it; pair::iterator,vector::iterator>::iterator,multimap::iterator,vector::iterator>::iterator> ret;

Can anyone please help me solve this problem. I can do it with simple vectors of int or string but I dont know how to compare a vector of structs in multimap.

for (vector::iterator itr = v.begin(); itr != v.end(); itr++) { cout << itr->x << " =>";

ret = mymm.equal_range(itr);

for (it = ret.first; it != ret.second; ++it)
{
    //c++;
    cout << " " << ((*it).second)->x << endl;
    }
 }

}

where MyPred is the struct containing int variables x, y, z.

Heidi