在此程序中,出现以下错误:
no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and '__gnu_cxx::__normal_iterator<std::__cxx11::basic_string<char>*, std::vector<std::__cxx11::basic_string<char> > >')
在以下代码中引用cout <<计数。我对C ++很陌生,不确定如何解决此问题。我查看了其他与错误类似的示例,但都没有发现与我有关的示例。如何解决此错误?我猜测它与vector :: size_type和vector.end()类型自动转换有关,无法计数并且无法转换为char或string,但是我该如何解决?
#include <algorithm>
#include <vector>
#include <iostream>
#include <string>
using namespace std;
ostream &print(ostream &os, const vector<string> &vs)
{
for(const auto &i: vs)
os << i << " ";
return os;
}
string make_plural(size_t ctr, const string &word, const string &ending = "s") {
return (ctr > 1) ? word + ending : word;
}
// if list used instead, no need for erase since it is default called unique
// member call
void elimDups(vector<string> &words)
{
sort(words.begin(), words.end());
auto end_unique = unique(words.begin(), words.end());
words.erase(end_unique, words.end());
print(cout, words);
}
void biggies(vector<string> &words, vector<string>::size_type sz)
{
elimDups(words); // alphabetize words order and remove dups
// sort words by size and alphabetize same size
stable_sort(words.begin(), words.end(),
[] (const string &a, const string &b)
{ return a.size() < b.size();});
// get an iterator to the first element whose size() is >= sz
auto wc = find_if(words.begin(), words.end(), [sz] (const string &a)
{ return a.size() >= sz; });
auto count = words.end() - sz;
cout << count << " "
<< make_plural(count, "word", "s")
<< " of length " << sz
<< " or longer" << endl;
// print words of the given size or longer, each one followed by a space
for_each(wc, words.end(), [] (const string &s)
{ cout << s << " ";});
cout << endl;
}
int main()
{
vector<string> vs2{"fox", "the", "jumps", "over",
"quick", "red", "slow", "red", "turtle"}
elimDups(vs);
elimDups(vs2);
return 0;
}
答案 0 :(得分:4)
函数void biggies(vector<string> &words, vector<string>::size_type sz)
中第38行的语句
auto count = words.end() - sz;
words.end()
部分为您提供了一个迭代器,然后您减去了一个标量,它又为您提供了一个迭代器。
因此变量count
是一个迭代器,而运算符<<
没有为迭代器定义。
您可以做的是:
auto count = words.size() - sz; // a number;
或
auto count = words.end() - wc; // a number;