函数具有2
参数。一种类型是类的向量(具有字符串私有变量(。另一个是它所寻找的字符串。我尝试了==
两个字符串,但它行不通。我期望它,但希望我可以在上面使用friend
,但似乎仅适用于2
类。
我尝试使用类Term
上的friend
函数进行搜索,但找不到使用一个类和一个功能的结果。除了friend
,我无法想到其他方式。
class Term
{
string str;
unsigned long long int weight;
Term(string s, long int w) : str(s), weight(w) {}
};
//my teacher provided this code so I can't change anything above
int FindFirstMatch(vector<Term> & records, string prefix)
//prefix is the word it looks for and returns the earliest time it appears.
{
for (int i=0; i<records.size(); i++)
{
if (records[i].str==prefix)
{
//I just need to get this part working
return i;
}
}
}`
它说str
是Term
的私人成员。这就是为什么我希望在其中简单地使用friend
的原因。
Term
类的所有成员均在private
监护权下,因此您甚至无法将其制作出一个实例。您的老师肯定会错过/或希望您弄清楚这一点。
除了friend
成员之外,您可以提供一个可以访问它的getter功能。
class Term
{
private:
std::string _str;
unsigned long long int weight;
public:
// constructor needs to be public in order to make an instance of the class
Term(const std::string &s, long int w) : _str(s), weight(w) {}
// provide a getter for member string
const std::string& getString() const /* noexcept */ { return _str; }
};
int FindFirstMatch(const std::vector<Term>& records, const std::string &prefix)
{
for (std::size_t i = 0; i < records.size(); i++)
{
if (records[i].getString() == prefix) // now you could access via getString()
{
return i;
}
}
return -1; // default return
}
或者如果允许您使用标准算法,例如使用 std :: find_if 和 std :: distance 。。。>
(请参阅LIVE(
#include <iterator>
#include <algorithm>
int FindFirstMatch(const std::vector<Term>& records, const std::string &prefix)
{
const auto iter = std::find_if(std::cbegin(records), std::cend(records), [&](const Term & term) { return term.getString() == prefix; });
return iter != std::cend(records) ? std::distance(std::cbegin(records) , iter) : -1;
}