如何将多套件传递到函数
-
24-10-2019 - |
题
我有一个非常简单的问题。我只是学习地图和多示例,并想知道如何将它们传递到功能中。我的大部分想法都包裹在多图上,但想一个快速的示例,说明如何将它们传递到空白功能中。
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"));
};
解决方案
为什么要通过指针?我认为最好传递参考(如果将地图在函数中修改)或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"));
};
其他提示
通过参考:
void calculateAverage(const multimap<string,int> & q)
但是然后通过指针还不错。只是语法看起来不好。
如果您选择通过指针,则可以在呼叫网站上使用此语法:
calculateAverage(&movies);
在我看来,在我看来,“本着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)
{
...
}
您正在尝试传递类型的价值 multimap<string,int>
作为指向该类型的指针,即 multimap<string,int>*
. 。要么将功能签名更改为 void calculateAverage(const multimap<string,int>& q)
并相应地修改其代码(替换 ->
和 .
),或这样称呼: calculateAverage(&movies)
.
不隶属于 StackOverflow