How to properly use a vector range constructor?

前端 未结 1 1629
无人及你
无人及你 2021-01-12 19:52

I want to load all the lines from a text file into a vector by using its range constructor and then output them through cout:

<         


        
相关标签:
1条回答
  • 2021-01-12 20:51

    You have fallen victim to the Most Vexing Parse, where the compiler sees your declaration as a function strings returning a vector<string>, taking two arguments:

    • an istream_iterator<string> called file
    • an unnamed pointer to function taking no arguments and returning a istream_iterator<string>.

    To eliminate the vexing parse, use an extra pair of parentheses around the first argument:

    vector<string> strings((istream_iterator<string>(file)) , istream_iterator<string>());
    //                     ^                              ^
    

    or, alternatively in C++11, use curly braces for the strings constructor

    vector<string> strings{istream_iterator<string>(file) , istream_iterator<string>()};
    //                    ^                                                           ^
    

    NOTE: Clang warns you about it through -Wvexing-parse (on by default).

    0 讨论(0)
提交回复
热议问题