Can someone explain why the top piece of code will not compile and the bottom one will?
#include <iterator>
#include <iostream>
#include <set>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
ifstream testFile;
testFile.open("opengl_functions", ios::in);
set<string> myset(istreambuf_iterator<string>(testFile), istreambuf_iterator<string>());
set<string>::iterator it;
for (it = myset.begin(); it != myset.end(); ++it ) {
}
}
//using namespace std;
//
//int main ()
//{
// int myints[] = {75,23,65,42,13};
// set<int> myset (myints,myints+5);
// set<int>::iterator it;
// cout << "myset contains:";
// for ( it=myset.begin() ; it != myset.end(); it++ )
// cout << " " << *it;
// cout << endl;
// return 0;
//}
—
[mehoggan@hogganz400 opengl_parser]$ make
g++ -o parser -Wall ./parser.cpp
./parser.cpp: In function ‘int main(int, char**)’:
./parser.cpp:17: error: request for member ‘begin’ in ‘myset’, which is of non-class type ‘std::set<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >(std::istreambuf_iterator<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::char_traits<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, std::istreambuf_iterator<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::char_traits<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > (*)())’
./parser.cpp:17: error: request for member ‘end’ in ‘myset’, which is of non-class type ‘std::set<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >(std::istreambuf_iterator<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::char_traits<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, std::istreambuf_iterator<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::char_traits<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > (*)())’
make: *** [parser] Error 1
Your compiler believes that myset is a function declaration. Look up “the most vexing parse”. I always run into it with istream iterators, so I always declare them beforehand. As a side benefit, I find it much easier to read:
However, I don’t believe that will compile either, but for a different reason. istreambuf_iterator can only be templated on character types. You’ll want to use an istream_iterator instead.