使用seekg时std::istreambuf_iterator相等

问题描述 投票:0回答:1

我对下面代码的输出感到困惑:

std::string content = "abcdefghijklmnopqrstuvwxyz1234567890";

std::istringstream iss(content);
iss.seekg(10);
std::istreambuf_iterator<char> it{iss}, end;
EXPECT_TRUE(iss.good());

iss.seekg(35);
std::istreambuf_iterator<char> it2{iss};
EXPECT_TRUE(iss.good());

iss.seekg(0);
std::istreambuf_iterator<char> it3{iss};
EXPECT_TRUE(iss.good());

bool oneAndTwo = it == it2;
bool twoAndThree = it2 == it3;
std::cout << std::boolalpha;
std::cout << oneAndTwo << std::endl;    // true
std::cout << twoAndThree << std::endl;  // true

std::cout << "char at the iterators: ";
std::cout << std::string(1, *it) << " "   // a
    << std::string(1, *it2) << " "        // a
    << std::string(1, *it3) << std::endl; // a

EXPECT_TRUE(iss.good());
std::string s1{it, end};  // abcdefghijklmnopqrstuvwxyz1234567890
std::cout << s1 << std::endl;

std::string s2{it2, end};  // a
std::cout << s2 << std::endl;

std::string s3{it3, end}; // a
std::cout << s3 << std::endl;

以及

std::cout
的输出:

true
true
char at the iterators: a a a
abcdefghijklmnopqrstuvwxyz1234567890
a
a

基于输出的两个问题:

  1. seekg
    对之后构建的
    std::istreambuf_iterator
    产生了影响。但是,如果我将一个迭代器与另一个迭代器进行比较,为什么所有迭代器都相等(
    it
    it2
    it3
    相等)?

  2. 如果它们确实相等,为什么它们构造的字符串不同?为什么

    it
    给出完整的字符串,而其他两个迭代器只给出第一个字符“a”?

数据流是否已损坏?我哪里搞砸了?

c++ stringstream istream istream-iterator seekg
1个回答
0
投票

seekg
对之后构建的
std::istreambuf_iterator
产生了影响。但是,如果我将一个迭代器与另一个迭代器进行比较(it、it2 和 it3 相等),为什么所有迭代器都相等?

因为

std::istreambuf_iterator
是一个单遍输入迭代器,它从为其构造的std::basic_streambuf对象中读取连续的字符(请参阅cppreference)。

因此在流中移动会影响所有迭代器。

如果它们确实相等,为什么它们构造的字符串不同?为什么它给我完整的字符串,而其他两个迭代器只给出第一个字符“a”?

因为当您构造第一个字符串时,您会消耗流。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.