'C++ vector initialization by using istream_iterator [duplicate]

my test.cpp:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;

int main()
{
    vector<int> vec(istream_iterator<int>(cin), istream_iterator<int>());
    // no error using std::cin
    // vector<int> vec(istream_iterator<int>(std::cin), istream_iterator<int>());
    sort(vec.begin(), vec.end());
    return 0;
}

complile with g++ and here is what I get:

test.cpp:12:11: error: request for member ‘begin’ in ‘vec’, which is of non-class type ‘std::vector<int>(std::istream_iterator<int>, std::istream_iterator<int> (*)())’
   12 |  sort(vec.begin(), vec.end());
c++


Solution 1:[1]

When I compiled this code with the options -Wall -Wextra -Werror, I got the following error messages:

iter-vec.cpp: In function ‘int main()’:
iter-vec.cpp:10:20: error: parentheses were disambiguated as a function declaration [-Werror=vexing-parse]
   10 |     vector<int> vec(istream_iterator<int>(cin), istream_iterator<int>());
      |                    
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
iter-vec.cpp:10:20: note: replace parentheses with braces to declare a variable
   10 |     vector<int> vec(istream_iterator<int>(cin), istream_iterator<int>());
      |                    
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      |                    -
      |                    {                                                   
-
      |                                                                        
}
iter-vec.cpp:13:14: error: request for member ‘begin’ in ‘vec’, which is of non-class type ‘std::vector<int>(std::istream_iterator<int>, std::istream_iterator<int> (*)())’
   13 |     sort(vec.begin(), vec.end());
      |              ^~~~~
iter-vec.cpp:13:27: error: request for member ‘end’ in ‘vec’, which is of non-class type ‘std::vector<int>(std::istream_iterator<int>, std::istream_iterator<int> (*)())’
   13 |     sort(vec.begin(), vec.end());
      |                           ^~~
cc1plus: all warnings being treated as errors

From this I concluded that it was a problem of the initialization of vec being ambiguous. When I removed the using namespace std; clause and added the appropriate std:: markers, I got the following to compile cleanly:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

int main()
{
    std::vector<int> vec(std::istream_iterator<int>(std::cin), 
                         std::istream_iterator<int>());
    std::sort(vec.begin(), vec.end());
    return 0;
}

I may not have gotten all the details correct, but I am fairly certain that this was the cause of the problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris