使用ostream_iterator将矢量struct复制到文件并复制

时间:2013-07-31 11:02:23

标签: c++ vector struct iterator ostream

我正在尝试在对矢量进行必要的更改后将矢量复制到新的文本文件。我可以很好地构建项目,但它给了我奇怪的错误,我不明白。有人可以帮我这个吗?

我的结构

class AccDetails {
public:
    string username;
    string name;
    string topicid;
    string testid;
};

给我错误的代码

vector<AccDetails>accInfo;
ofstream temp ("temp.txt");
ostream_iterator<AccDetails>temp_itr(temp,"\n");
copy(accInfo.begin(),accInfo.end(),temp_itr); 

有一大堆错误行,但我认为这应该是重要的两行: enter image description here

2 个答案:

答案 0 :(得分:3)

您需要为operator<<重载AccDetails。这是ostream_iterator内部调用的内容。

这样的事情:

std::ostream& operator<<(std::ostream& stream, const AccDetails& obj)
{   
    // insert objects fields in the stream one by one along with some
    // description and formatting:

    stream << "User Name: " << obj.username << '\n'
           << "Real Name: " << obj.name << '\n'
           << obj.topicid << ' ' << obj.testid << '\n';

    return stream;
}

运算符将其插入的流作为第一个参数,并将其作为第二个流的对象的常量引用(这也允许传递临时AccDetails)。现在你也可以说:

AccDetails acc;
std::cout << acc;

如果运营商需要访问AccDetail的私人字段,则需要声明为friend

如果您不熟悉运算符重载,建议您阅读this SO thread

希望有所帮助。

答案 1 :(得分:2)

在超载后可以有这个,因为jrok说:

class AccDetails 
{

    std::string username;
    std::string name;
    std::string topicid;
    std::string testid;

    friend std::ostream& operator<<(std::ostream&, const AccDetails&);
    friend std::istream& operator>>(std::istream& is,  AccDetails& );
};

std::ostream& operator<<(std::ostream& os, const AccDetails& acc)
{
    os  << "User Name: " << acc.username << std::endl
           << "Name: " << acc.name << std::endl
           << acc.topicid << ' ' << acc.testid << std::endl;
    return os;
}

std::istream& operator>>(std::istream& is,  AccDetails& acc)
{   
    is >> acc.username >>acc.name >> acc.topicid >> acc.testid ;
    return is;
}


int main()
{

std::vector<AccDetails>accInfo;

std::copy(std::istream_iterator<AccDetails>(std::cin),
    std::istream_iterator<AccDetails>(),std::back_inserter(accInfo) ); 

std::ofstream temp("temp.txt",std::ios::out);
std::ostream_iterator<AccDetails>temp_itr(temp,"\n");
std::copy(accInfo.begin(),accInfo.end(),temp_itr); 

}