0

我有一个非常简单的问题。我只是学习地图和多地图,想知道如何将它们传递给函数。我的大部分时间都围绕着多图,但想要一个关于如何将它们传递给 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

4 回答 4

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"));
};
于 2011-03-15T15:54:38.393 回答
1

通过引用传递:

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

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

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

calculateAverage(&movies);
于 2011-03-15T15:54:03.340 回答
1

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

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

定义如下:

typedef multimap<string,int>::const_iterator MapIt;
void calculateAverage(const MapIt &begin, const MapIt &end)
{
...
}
于 2012-02-09T18:58:01.237 回答
0

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

于 2011-03-15T15:55:54.430 回答