What does this C ++ / C ++ 11 construct mean?

I have a short piece of code. I donโ€™t understand what this design is. I know this piece of code reads numbers from input and counts its frequency in unordered_map. But what is it [&]? And what's the point (int x)? What does it mean input(cin)? I mean "cin" in parentheses? And how can for_each iterate over input(cin)an empty eof parameter? I do not understand this whole construction.

unordered_map<int,int> frequency;
istream_iterator<int> input(cin);
istream_iterator<int> eof;

for_each(input, eof, [&] (int x)
    { frequency[x]++; });
+5
source share
3 answers

istream_iteratorallows you to iteratively retrieve elements from istreamthat you pass to the constructor. The object eofis explained as follows:

: end-the-stream; , ( void *, , false) ( basic_istream).

for_each - , # 1 , # 2. , cin ( ) , - - input eof, .

[&] (int x) { frequency[x]++; } ; inline.

unordered_map<int,int> frequency; // this NEEDS to be global now
istream_iterator<int> input(cin);
istream_iterator<int> eof;

void consume(int x) {
    frequency[x]++;
}

for_each(input, eof, consume);

, : , , .

+6

.

  • . std::istream_iterator<T> std::istream & s, { T x; s >> x; return x; }. , , , "end".

    . :

    std::vector<int> v(std::istream_iterator<int>(std::cin),
                       std::istream_iterator<int>());
    
    std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
    
  • ++ 11 -, ( ). :

    auto f = [](int a, int b) -> double { return double(a) / double(b); };
    
    auto q = f(1, 2);  // q == 0.5
    

    f , , - . ( !) , auto.

    Lambdas , , . :

    auto f = [&frequency](int x) -> void { ++frequency[x]; };
    

    , . :

    struct F
    {
        F(std::unordered_map<int, int> & m) : m_(m) { }
        void operator()(int x) { ++m_[x]; }
    private:
        std::unordered_map<int, int> & m_;
    } f;
    

& , . [=] [&], .

+2

This is STL std :: for_each (non-C ++ 11), iterating through input until there is eof ; lambda call [&] (int x) { frequency[x]++; }for each value

So, this code calculates the symbol rate in istream; saving them in the map

+1
source

All Articles