Hello.
I have a map

map<int, vector<int> >

and I want to find which one of the vectors has the most elements.
Is there a built in function that does that or do I have to write my one code.

Cheers
Costantinos

you could try std::max_element in <algorithm>

Thanx.
My question was a bit different since I was trying to find the vector with the most elements, not the biggest element.
I have written a small function for doing so

Cheers
Constantinos

std::max_element takes an optional binary predicate as its third parameter. You could use it on your container holding the vectors (the map) and define a predicate that compares the size of two vectors. However, I'm not sure max_element would have been the best solution in this case, anyways.

Comments
Nice--[Grunt]

Maybe you're trying to do something like this:

#include <iostream>
#include <map>
#include <vector>
using namespace std;
 
int main ()
{
    map < int, vector<int> > map_cont;
    vector <int> v1;
    vector <int> v2;
    vector <int> v3;
    int i;
    for (i = 0; i < 10; i++)
    {
        v1.push_back(i);
    }
    for (i = 0; i < 20; i++)
    {
        v2.push_back(i);
    } 
    for (i = 0; i < 5; i++)
    {
        v3.push_back(i);
    }
    map_cont[1] = v1;
    map_cont[2] = v2;
    map_cont[3] = v3;
    map < int, vector<int> > :: iterator it_trav, it_max;
    
    it_max = map_cont.begin();
    for (it_trav = map_cont.begin(); it_trav != map_cont.end(); ++it_trav)
    {
        if ( it_max->second.size() < it_trav->second.size() )
        {
            it_max = it_trav;
        }
    }
    
    cout << "Element with vector of max. no. of elements:" << it_max->second.size();
    cout << " and it's map[" << it_max->first << "]!" << endl;
}

This code is just for demonstration. I hope it helps!

Micko

Comments
Nice--[Grunt]

I understood he's trying to find element in container whose vector has max number of elements.

I understood he's trying to find element in container whose vector has max number of elements.

Yeah you're right, I missed that. I was just skimming through this thread. You were using the .size() call anyway.

This article has been dead for over six months. Start a new discussion instead.