c++ - 将 vector 输出到文件中

标签 c++

我正在尝试编写一个程序来打开一个包含此格式的名称列表的 txt 文件(忽略项目符号):

  • 3分
  • 4 拉尔夫
  • 1 版
  • 2 凯文

并会根据前面的数字创建一个带有组织名称的文件:

  • 1 版
  • 2 凯文
  • 3分
  • 4 拉尔夫

我无法将 vector 输出到新文件“outfile.txt” 在第 198 行,我收到错误消息“不匹配‘operator<<...”

我还可以使用哪些其他方法来输出 vector ?

#include <iostream>
#include <fstream>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <iterator>



using namespace std;

struct info
{
    int order;
    string name;
};

int sortinfo(info a, info b)
{
    return a.order < b.order;
}

int main()
{
    ifstream in;
    ofstream out;
    string line;
    string collection[5];
    vector <string> lines;
    vector <string> newLines;
    in.open("infile.txt");
    if (in.fail())
    {
        cout << "Input file opening failed. \n";
        exit(1);
    }
    out.open("outfile.txt");
    if (out.fail())
    {
        cout << "Output file opening failed. \n";
        exit(1);
    }

vector <info> inf;

while(!in.eof())
{
    info i;
    in >> i.order;
    getline(in, i.name);

    inf.push_back(i);
}

sort(inf.begin(), inf.end(), sortinfo);


ostream_iterator <info> output_iterator(out, "\n");
copy (inf.begin(), inf.end(), output_iterator);

in.close( );
out.close( );

return 0;
}

最佳答案

您需要重载 operator<<对于 info :

std::ostream& operator<< (std::ostream& stream, const info& inf) {
    return stream << inf.order << " " << inf.name;
}

关于c++ - 将 vector 输出到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27026594/

相关文章:

c++ - 如何找到 vector 中 5 个最大元素的索引?

c++ - 是否可以将宏函数作为 QMetaMethod 标记?

c++ - 将 OpenCV 链接到 XCode

c++ - 结构到字符串,反之亦然

c++ - Makefile 和嵌套的头文件

c++ - 将数据成员的生命周期限制为一种方法

c++ - 比较和拆分文本文件中的字符串

C++ 指针或内存

c++ - 我在使用算法的库排序功能时遇到问题

c++ - 尝试将纹理映射到 GLSL 中的三角形时发生访问冲突