gpt4 book ai didi

c++ - 继续获取 "no match for ' operator<<' C++

转载 作者:行者123 更新时间:2023-11-30 01:19:13 25 4
gpt4 key购买 nike

我正在编写一个程序来从文件中读取文本,我需要打印出每个数字在文件中出现的位置。例如,.txt 文件如下所示:

one
two one two
three three two one

我的输出应该是这样的:

one: 0, 2, 7
two: 1, 3, 6
three: 4, 5

一切正常,直到我尝试显示类型为字符串 list(int) 的映射,然后我得到了整个“'operator<<' 不匹配”错误。这是我的代码,任何帮助将不胜感激,谢谢!

#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <list>
#include <vector>

using namespace std;

int main()
{
ifstream is("input.txt");
if (is.fail())
{
cout << "File I/O error!" << endl;
exit(1);
}

map<string, list<int> > m;
string word;
vector<string> v;
list<int> l, x, y;
while (is >> word)
{
v.push_back(word);
}

for (unsigned int i = 0; i < v.size(); ++i)
{
if (v[i] == "one")
l.push_back(i);
else if (v[i] == "two")
x.push_back(i);
else if (v[i] == "three")
y.push_back(i);
}

m["One"] = l;
m["Two"] = x;
m["Three"] = y;

for (map<string, list<int> >::iterator i = m.begin(); i != m.end(); ++i)
cout << (*i).first << ", " << (*i).second << endl;

return 0;
}

最佳答案

问题是当您尝试输出 (*i).second 时.作为i类型为 map<string, list<int> >::iterator (*i).secondlist<int>c++不知道如何输出它。

你有两个选择 - 要么重载 ostream& operator<<(ostream& out, const list<int>& l)或者使用内循环将元素一个一个输出。我个人推荐第二种选择,因为为这种“流行”类型重载运算符可能很危险。

关于c++ - 继续获取 "no match for ' operator<<' C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21155681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com