gpt4 book ai didi

c++ - 重载 istream 运算符>> c++

转载 作者:太空宇宙 更新时间:2023-11-03 10:34:35 25 4
gpt4 key购买 nike

假设我有一个字符 vector ,我将它作为字符串而不是字符 vector 推送到流中,我如何使用运算符>>取回字符 vector ?

class C{
private:
vector<char> c;

public:
C(string str){
for(int x = 0; x < str.size(); x++)
c.push_back(str[x]);
}

vector<char> data(){
return c;
}
};

ostream operator<<(ostream & stream, C & in){
for(int x = 0; x < in.data().size(); x++)
stream << in.data()[x];
return stream;
}

istream operator>>(istream & stream, C & in){
// ???
// what kind of loop?
}

最佳答案

我会这样写你的例子....

#include <algorithm>
#include <iterator>
#include <vector>
#include <iostream>
#include <sstream>

class C
{
std::vector<char> mData;

public:
// Constructor, note im using the iterator range
// vector constructor.
C(const std::string& str)
: mData(str.begin(), str.end())
{
}

// Returning data by const reference to avoid
// copying a potentially large object.
const std::vector<char>& data() const
{
return mData;
}

// declared the input operator as a friend as I need it to
// access mData - alternatively you could write a "loadFromStream"
// type function that does the same, declare this as non-friend, and call that.
friend std::istream& operator>>(std::istream& is, C& c);
};

std::ostream& operator<<(std::ostream& os, const C& c)
{
// Use an ostream_iterator to handle output of the vector
// using iterators.
std::copy(c.data().begin(),
c.data().end(),
std::ostream_iterator<char>(os, ""));

return os;
}

std::istream& operator>>(std::istream& is, C& c)
{
// load the data using the assign function, which
// clears any data already in the vector, and copies
// in the data from the specified iterator range.
// Here I use istream_iterators, which will read to the end
// of the stream. If you dont want to do this, then you could
// read what you want into a std::string first and assign that.
c.mData.assign(std::istream_iterator<char>(is),
std::istream_iterator<char>());

return is;
}

int main()
{
C c("Hello");

std::stringstream ss;
ss << c;

std::cout << ss.str() << std::endl;

C d("");
ss >> d;

std::cout << d.data().size() << std::endl;

return 0;
}

关于c++ - 重载 istream 运算符>> c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6487230/

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