0
votes

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?

2
You may provide custom comparator that use sum of elements, is that what you need? - Slava
This code actually gives you output? It shouldn't since you never set iter to a valid iterator. - NathanOliver
std::sort is a thing and, conveniently, it can take a custom comparison function. - Jesper Juhl
You really ought to avoid using namespace std - it is a bad habit to get into, and can silently change the meaning of your program when you're not expecting it. Get used to using the namespace prefix (std is intentionally very short), or importing just the names you need into the smallest reasonable scope. - Toby Speight

2 Answers

5
votes

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 ;
}
2
votes

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 )