std::istream_iterator<>与 copy_n() 和朋友

发布于 2024-10-18 23:26:57 字数 933 浏览 3 评论 0 原文

下面的代码片段从 std::cin 读取三个整数;它将两个写入 numbers 并丢弃第三个:

std::vector<int> numbers(2);
copy_n(std::istream_iterator<int>(std::cin), 2, numbers.begin());

我希望代码从 std::cin 中读取两个整数,但事实证明这是正确的,符合标准的行为。这是标准中的疏忽吗?这种行为的理由是什么?


从 C++03 标准中的 24.5.1/1 开始:

构建完成后,每个 使用 time ++ 时,迭代器读取 并存储值T

因此,在上面的代码中,在调用时流迭代器已经读取了一个整数。从那时起,算法中迭代器的每次读取都是预读,产生前一次读取缓存的值。

下一个标准的最新草案 n3225 似乎没有任何变化这里(24.6.1/1)。

在相关说明中,当前标准的 24.5.1.1/2 参考 istream_iterator(istream_type& s) 构造函数读取

效果:初始化in_stream svalue 可能会在期间初始化 施工或第一次 参考。

强调“可以被初始化......”而不是“被初始化”。这听起来与 24.5.1/1 相矛盾,但也许这本身就值得一个问题。

The snippet below reads three integers from std::cin; it writes two into numbers and discards the third:

std::vector<int> numbers(2);
copy_n(std::istream_iterator<int>(std::cin), 2, numbers.begin());

I'd expect the code to read exactly two integers from std::cin, but it turns out this is a correct, standard-conforming behaviour. Is this an oversight in the standard? What is the rationale for this behaviour?


From 24.5.1/1 in the C++03 standard:

After it is constructed, and every
time ++ is used, the iterator reads
and stores a value of T.

So in the code above at the point of call the stream iterator already reads one integer. From that point onward every read by the iterator in the algorithm is a read-ahead, yielding the value cached from the previous read.

The latest draft of the next standard, n3225, doesn't seem to bear any change here (24.6.1/1).

On a related note, 24.5.1.1/2 of the current standard in reference to the istream_iterator(istream_type& s) constructor reads

Effects: Initializes in_stream with
s. value may be initialized during
construction or the first time it is
referenced.

With emphasis on "value may be initialized ..." as opposed to "shall be initialized". This sounds contradicting with 24.5.1/1, but maybe that deserves a question of its own.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

韬韬不绝 2024-10-25 23:26:57

不幸的是,copy_n 的实现者未能考虑复制循环中的预读。 Visual C++ 实现在 stringstream 和 std::cin 上都按照您的预期工作。我还检查了原始示例中 istream_iterator 是在线构造的情况。

下面是 STL 实现中的关键代码。

template<class _InIt,
    class _Diff,
    class _OutIt> inline
    _OutIt _Copy_n(_InIt _First, _Diff _Count,
        _OutIt _Dest, input_iterator_tag)
    {   // copy [_First, _First + _Count) to [_Dest, ...), arbitrary input
    *_Dest = *_First;   // 0 < _Count has been guaranteed
    while (0 < --_Count)
        *++_Dest = *++_First;
    return (++_Dest);
    }

这是测试代码

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

int _tmain(int argc, _TCHAR* argv[])
{
    std::stringstream ss;
    ss << 1 << ' ' << 2 << ' ' << 3 << ' ' << 4 << std::endl;
    ss.seekg(0);
    std::vector<int> numbers(2);
    std::istream_iterator<int> ii(ss);
    std::cout << *ii << std::endl;  // shows that read ahead happened.
    std::copy_n(ii, 2, numbers.begin());
    int i = 0;
    ss >> i;
    std::cout << numbers[0] << ' ' << numbers[1] << ' ' << i << std::endl;

    std::istream_iterator<int> ii2(std::cin);
    std::cout << *ii2 << std::endl;  // shows that read ahead happened.
    std::copy_n(ii2, 2, numbers.begin());
    std::cin >> i;
    std::cout << numbers[0] << ' ' << numbers[1] << ' ' << i << std::endl;

    return 0;
}


/* Output
1
1 2 3
4 5 6
4
4 5 6
*/

Unfortunately the implementer of copy_n has failed to account for the read ahead in the copy loop. The Visual C++ implementation works as you expect on both stringstream and std::cin. I also checked the case from the original example where the istream_iterator is constructed in line.

Here is the key piece of code from the STL implementation.

template<class _InIt,
    class _Diff,
    class _OutIt> inline
    _OutIt _Copy_n(_InIt _First, _Diff _Count,
        _OutIt _Dest, input_iterator_tag)
    {   // copy [_First, _First + _Count) to [_Dest, ...), arbitrary input
    *_Dest = *_First;   // 0 < _Count has been guaranteed
    while (0 < --_Count)
        *++_Dest = *++_First;
    return (++_Dest);
    }

Here is the test code

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

int _tmain(int argc, _TCHAR* argv[])
{
    std::stringstream ss;
    ss << 1 << ' ' << 2 << ' ' << 3 << ' ' << 4 << std::endl;
    ss.seekg(0);
    std::vector<int> numbers(2);
    std::istream_iterator<int> ii(ss);
    std::cout << *ii << std::endl;  // shows that read ahead happened.
    std::copy_n(ii, 2, numbers.begin());
    int i = 0;
    ss >> i;
    std::cout << numbers[0] << ' ' << numbers[1] << ' ' << i << std::endl;

    std::istream_iterator<int> ii2(std::cin);
    std::cout << *ii2 << std::endl;  // shows that read ahead happened.
    std::copy_n(ii2, 2, numbers.begin());
    std::cin >> i;
    std::cout << numbers[0] << ' ' << numbers[1] << ' ' << i << std::endl;

    return 0;
}


/* Output
1
1 2 3
4 5 6
4
4 5 6
*/
山田美奈子 2024-10-25 23:26:57

今天我遇到了非常相似的问题,这里是例子:

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

struct A
{
    float a[3];
    unsigned short int b[6];
};

void ParseLine( const std::string & line, A & a )
{
    std::stringstream ss( line );

    std::copy_n( std::istream_iterator<float>( ss ), 3, a.a );
    std::copy_n( std::istream_iterator<unsigned short int>( ss ), 6, a.b );
}

void PrintValues( const A & a )
{
    for ( int i =0;i<3;++i)
    {
        std::cout<<a.a[i]<<std::endl;
    }
    for ( int i =0;i<6;++i)
    {
        std::cout<<a.b[i]<<std::endl;
    }
}

int main()
{
    A a;

    const std::string line( "1.1 2.2 3.3  8 7 6 3 2 1" );

    ParseLine( line, a );

    PrintValues( a );
}

用 g++ 4.6.3 编译上面的例子会产生一个:

1.1 2.2 3.3 7 6 3 2 1 1

,用 g++ 4.7.2 编译会产生另一个结果:

1.1 2.2 3.3 8 7 6 3 2 1

c++11 标准告诉了这个关于 copy_n 的信息

template<class InputIterator, class Size, class OutputIterator>
OutputIterator copy_n(InputIterator first, Size n, OutputIterator result);

效果:对于每个非负整数 i < n,执行 *(结果 + i) = *(第一个 + i)。
返回:结果+n。
复杂性:正好有 n 个作业。

正如您所看到的,没有指定迭代器到底发生了什么,这意味着它依赖于实现。

我的观点是,您的示例不应读取第三个值,这意味着这是标准中的一个小缺陷,因为他们没有指定行为。

Today I encountered very similar problem, and here is the example:

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

struct A
{
    float a[3];
    unsigned short int b[6];
};

void ParseLine( const std::string & line, A & a )
{
    std::stringstream ss( line );

    std::copy_n( std::istream_iterator<float>( ss ), 3, a.a );
    std::copy_n( std::istream_iterator<unsigned short int>( ss ), 6, a.b );
}

void PrintValues( const A & a )
{
    for ( int i =0;i<3;++i)
    {
        std::cout<<a.a[i]<<std::endl;
    }
    for ( int i =0;i<6;++i)
    {
        std::cout<<a.b[i]<<std::endl;
    }
}

int main()
{
    A a;

    const std::string line( "1.1 2.2 3.3  8 7 6 3 2 1" );

    ParseLine( line, a );

    PrintValues( a );
}

Compiling the above example with g++ 4.6.3 produces one:

1.1 2.2 3.3 7 6 3 2 1 1

, and compiling with g++ 4.7.2 produces another result :

1.1 2.2 3.3 8 7 6 3 2 1

The c++11 standard tells this about copy_n :

template<class InputIterator, class Size, class OutputIterator>
OutputIterator copy_n(InputIterator first, Size n, OutputIterator result);

Effects: For each non-negative integer i < n, performs *(result + i) = *(first + i).
Returns: result + n.
Complexity: Exactly n assignments.

As you can see, it is not specified what exactly happens with the iterators, which means it is implementation dependent.

My opinion is that your example should not read the 3rd value, which means this is a small flaw in the standard that they haven't specified the behavior.

北渚 2024-10-25 23:26:57

我不知道确切的理由,但由于迭代器还必须支持运算符 *(),因此它必须缓存它读取的值。允许迭代器在构造时缓存第一个值可以简化这一过程。当流最初为空时,它还有助于检测流结束。

也许您的用例是委员会没有考虑的一个?

I don't know the exact rationale, but as the iterator also has to support operator*(), it will have to cache the values it reads. Allowing the iterator to cache the first value at construction simplifies this. It also helps in detecting end-of-stream when the stream is initially empty.

Perhaps your use case is one the committee didn't consider?

你穿错了嫁妆 2024-10-25 23:26:57

今天,在你九年后的今天,我遇到了同样的问题,所以按照这个线程,在解决这个问题时注意到了这一点,似乎我们可以在第一次之后每次读取时将迭代器走一步(我的意思是 cin< /code> 也不能自动忽略换行符结尾,我们用 cin.ignore() 来帮助它,我猜我们也可以帮助这个实现):

    #include<bits/stdc++.h>
    using namespace std;

    int main(){

    freopen("input.txt","r",stdin);

    istream_iterator<int> it(cin);

    ostream_iterator<int> cout_it(cout, " ");

    copy_n(it, 5, cout_it);

    cout<<"\nAnd for the rest of the stream\n";

    for(int i=0;i<10;i++){

        it++;

        copy_n(it, 1, cout_it);

      }

    return 0;
   }

并且应该产生如下输出:

1 2 3 4 5
And for the rest of the stream
6 7 8 9 10 11 12 13 14 15

Today, 9 years after you, I fell into the same problem, So following this thread, while playing with the problem noticed this, It seems we can walk the iterator one step for each reading after first time(I mean cin also can't ignore end of line feed automatically, we help it with cin.ignore(), we can help this implementation too I guess):

    #include<bits/stdc++.h>
    using namespace std;

    int main(){

    freopen("input.txt","r",stdin);

    istream_iterator<int> it(cin);

    ostream_iterator<int> cout_it(cout, " ");

    copy_n(it, 5, cout_it);

    cout<<"\nAnd for the rest of the stream\n";

    for(int i=0;i<10;i++){

        it++;

        copy_n(it, 1, cout_it);

      }

    return 0;
   }

and that should produce output like:

1 2 3 4 5
And for the rest of the stream
6 7 8 9 10 11 12 13 14 15
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文