如何将多图传递到函数中

时间:2011-03-15 15:50:53

标签: c++ function parameter-passing multimap

我有一个非常简单的问题。我只是学习地图和多图,想知道如何将它们传递给一个函数。我的大部分思绪都围绕着多图,但是想要一个关于如何将它们传递给void函数的快速示例。

int main()
{
multimap<string,int> movies;


movies.insert(pair<string,int>("Happy Feet",6));
movies.insert(pair<string,int>("Happy Feet",4));
movies.insert(pair<string,int>("Pirates of the Caribbean",5));
movies.insert(pair<string,int>("Happy Feet",3));
movies.insert(pair<string,int>("Pirates of the Caribbean",4));
movies.insert(pair<string,int>("Happy Feet",4));
movies.insert(pair<string,int>("Flags of out Fathers",4));
movies.insert(pair<string,int>("Gigli",4));

cout<<"There are "<<movies.count("Happy Feet")<<" instances of "<<"Happy Feet"<<endl;
cout<<"There are "<<movies.count("Pirates of the Caribbean")<<" instances of "<<"Pirates of the Caribbean"<<endl;
cout<<"There are "<<movies.count("Flags of out Fathers")<<" instances of "<<"Flags of out Fathers"<<endl;
cout<<"There are "<<movies.count("Gigli")<<" instances of "<<"Gigli"<<endl;



system("PAUSE");
calculateAverage(movies);  // this is where im getting errors such as no conversions
return 1;
}
void calculateAverage(multimap<string,int> *q)
{
// this function wont calculate the average obviously. I just wanted to test it
int averageH;
int averageP;
int averageF;
int averageG;

averageH = (q->count("Happy Feet"));
averageP = (q->count("Happy Feet"));
averageF = (q->count("Happy Feet"));
averageG = (q->count("Happy Feet"));


};

4 个答案:

答案 0 :(得分:3)

为什么要通过指针?我认为最好传递一个引用(如果要在函数内修改映射)或引用const否则

void calculateAverage(const multimap<string,int> & q)
{
// this function wont calculate the average obviously. I just wanted to test it
int averageH;
int averageP;
int averageF;
int averageG;

averageH = (q.count("Happy Feet"));
averageP = (q.count("Happy Feet"));
averageF = (q.count("Happy Feet"));
averageG = (q.count("Happy Feet"));
};

答案 1 :(得分:1)

通过引用传递:

void calculateAverage(const multimap<string,int> & q)

但是传递指针并不是那么糟糕。只是语法看起来不太好。

如果您选择传递指针,那么在调用站点,您将使用以下语法:

calculateAverage(&movies);

答案 2 :(得分:1)

在我看来,更多“在STL的精神中”将迭代器movies.begin()movies.end()传递给calculateAverage函数。例如:

calculateAverage(movies.begin(),movies.end());

定义如下:

typedef multimap<string,int>::const_iterator MapIt;
void calculateAverage(const MapIt &begin, const MapIt &end)
{
...
}

答案 3 :(得分:0)

您尝试传递类型multimap<string,int>的值作为指向该类型的指针,即multimap<string,int>*。将函数签名更改为void calculateAverage(const multimap<string,int>& q)并相应地修改其代码(将->替换为.),或者将其调用为:calculateAverage(&movies)