Sau đây là an example from cppreference.com,Confused về việc sử dụng 'std :: istreambuf_iterator'
The Code is:
#include <vector>
#include <sstream>
#include <iostream>
#include <iterator>
int main()
{
// typical use case: an input stream represented as a pair of iterators
std::istringstream in("Hello, world");
std::vector<char> v((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
std::cout << "v has " << v.size() << " bytes. ";
v.push_back('\0');
std::cout << "it holds \"" << &v[0] << "\"\n";
// demonstration of the single-pass nature
std::istringstream s("abc");
std::istreambuf_iterator<char> i1(s), i2(s);
std::cout << "i1 returns " << *i1 << '\n'
<< "i2 returns " << *i2 << '\n';
++i1;
std::cout << "after incrementing i1, but not i2\n"
<< "i1 returns " << *i1 << '\n'
<< "i2 returns " << *i2 << '\n';
++i2; // this makes the apparent value of *i2 to jump from 'a' to 'c'
std::cout << "after incrementing i2, but not i1\n"
<< "i1 returns " << *i1 << '\n'
<< "i2 returns " << *i2 << '\n';
}
Tôi có hai câu hỏi:
- Ai đó có thể xây dựng trên mã
std::vector<char> v((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
, tôi không hoàn toàn hiểu những gì nó có đang làm .. và tại sao chúng ta có thể in chuỗi "Xin chào, thế giới" chỉ bằng cách sử dụngcout<<&v[0]
- Tại sao giá trị học nghề của * i2 nhảy cho "a" đến "c"? ai đó có thể giải thích cơ chế của nó?
Cảm ơn bạn rất nhiều!
Ngoài ra, làm cách nào để có thể in thư dưới dạng '& v [0]'? :) – 0x499602D2
Vì 'v [0]' là một 'char' nên' & v [0] 'là một' char * ' –
Rất chi tiết! Cảm ơn câu trả lời của bạn!!!! –