我在c ++上仍然相当生气,而且我无法理解我的问题。我收到的错误消息是“No operator”<<'匹配这些操作数“我有的代码:
for(int i = 0; i < ruleList.size(); i++)
{
cout << ruleList[i].lhs << endl;
cout << ruleList[i].rhs << endl; // Problem printing this
}
struct Rules
{
string lhs;
vector<string> rhs;
}rule;
vector<Rules> ruleList;
这是否适合这样做?我以同样的方式做了lhs并且工作正常。
rule.rhs.push_back(token);
ruleList.push_back(rule);
答案 0 :(得分:1)
标准容器没有定义operator<<
。您将需要编写一个打印函数,类似于:
void print(std::ostream& out, std::vector<std::string> const & data) {
std::copy(data.begin(), data.end(),
std::ostream_iterator<std::string>(out, " "));
}
然后将其用作:
print(std::cout, ruleList[i].rhs);
答案 1 :(得分:1)
std::vector
未定义operator <<
。您可以使用std::ostream_iterator
格式化列表:
std::copy( ruleList[i].rhs.begin(), ruleList[i].rhs.end(),
std::ostream_iterator< std::string >( std::cout, ", " ) );
这有点不完美,因为在最终元素之后打印", "
,但这可以解决。
答案 2 :(得分:0)
您需要为<<
编写自己的struct rules
运算符。它应该在C ++ 11中看起来像这样:
struct rules {
string lhs;
std::vector<std::string> rhs;
// apparently it's a good idea to keep this out of std:: namespace
inline static std::ostream & operator << (std::ostream & out, const rules & r) {
out << r.lhs << std::endl;
//for (int i = 0; i < v.length(); i++)
for (auto & s : r.rhs) {
out << s;
}
out << std::endl;
return out;
}
}
MSDN在此处写了:http://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx