grace1997
grace1997

Reputation: 41

multimap<vector<int> > ,char> how to sort it?

Here's the code, it can compile, but it can't run, why?:

#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main() {
    typedef multimap<vector< int >, char> mmap;

    mmap foo;
    vector<int> v;
    v.push_back(15);
    v.push_back(14);
    foo.insert(pair<vector< int >, char> (v, 'b'));
    v.clear();
    v.push_back(15);
    v.push_back(80);
    foo.insert(pair<vector< int >, char> (v, 'c'));
    v.clear();
    v.push_back(9);
    v.push_back(17);
    foo.insert(pair<vector< int >, char> (v, 'a'));
    v.clear();

    mmap::iterator iter;

    for (int i = 0; i < iter->first.size(); ++i) {
        wcout << iter->first[i] << " ";
        for (iter = foo.begin(); iter != foo.end(); ++iter) {
            wcout << iter->second << " ";
        }
        wcout << endl;
    }
}

output:

15 80 c

15 14 b

9 17 a

I want to plus the integer,then sort it : (order the numbers from greatest to least

80+15>15+14>9+17

how to do that?

Upvotes: 0

Views: 159

Answers (2)

R Sahu
R Sahu

Reputation: 206607

You will need to use a custom compare function/functor to help you with that.

struct Compare
{
   bool operator()(std::vector<int> const& lhs, std::vector<int> const& rhs) const
   {
      int sum1 = std::accumulate(lhs.begin(), lhs.end(), 0);
      int sum2 = std::accumulate(rhs.begin(), rhs.end(), 0);
      return (sum1 > sum2); // Not sum1 < sum2, if I understood your question
   }
};

and use:

typedef multimap<vector< int >, char, Compare> mmap;

You'll also have to fix the code that prints the contents of foo.

mmap::iterator iter = foo.begin();
for ( ; iter != foo.end(); ++iter )
{
   for ( size_t i = 0 ; i < iter->first.size() ; ++i ) {
      wcout << iter->first[i] << " " ;
   }
   wcout << iter->second << " " ;
   wcout << endl ;
}

Upvotes: 5

Jason
Jason

Reputation: 2671

You initialized iter in your inner for loop:

for ( iter = foo.begin() ; iter != foo.end() ; ++iter )

However, you try to access in the outer for loop where it points to nothing:

for ( int i = 0 ; i < iter->first.size() ; ++i )

Upvotes: 2

Related Questions