使用 cplusplus.com 中的代码,我试图在 vector<std::string>
中找到最大的 int 值.
vector 是 std::string 格式,这里别无选择。
bool myfn(int i, int j)
{
return i < j;
}
vector<std::string> dat;
dat.push_back(2.1);
dat.push_back(5.3);
for (int l = 0; l < dat.size(); ++l)
{
std::cout << *std::max_element(dat.begin(), dat.end(), myfn) << '\n';
}
预期输出:
3
错误:
.cpp:76:93: error: no matching function for call to 'max_element(std::vector<std::basic_string<char> >&, std::vector<std::basic_string<char> >::size_type, bool (&)(int, int))'
如何找到 vector<std::string>
中的最大值?
最佳答案
您正在调用 max_element
用错误的论点。它需要两个迭代器和一个函数:
template <class ForwardIterator, class Compare>
ForwardIterator max_element (ForwardIterator first, ForwardIterator last,
Compare comp);
你用一个 vector 和一个大小来调用它。混淆可能源于您链接的引用示例:
std::min_element(myints, myints +7, myfn)
// ^^^^^^ ^^^^^^^^^
// int* int*
在这种情况下,myints
和 myints + 7
类型为 int*
,原始指针是一个迭代器。但是,在您的情况下,您传递了两种不同 类型( vector<string>
和 size_t
),两者 都不是迭代器。所以你需要改为:
*std::max_element(dat.begin(), dat.end(), myfn)
或者,为了说明与引用中的示例等效的内容(尽管肯定更喜欢上面的示例):
std::string* first = &dat[0];
*std::max_element(first, first + dat.size(), myfn)
之所以可行,是因为在本例中我传递了两个 string*
的,它们是迭代器。
(同样根据您的使用情况,dat
应该是 vector<int>
而不是 vector<string>
。)
关于c++ - 如何从 vector<std::string> 获取 max_element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27140216/