Page 1 of 1

Intermediate HW 16 - Problem 2 error with istream_iterator

Posted: May 8th, 2019, 2:52 pm
by ac11b
I have been a huge fan of the Chili C++ series' for a while, and was working on the solution for problem 2 in the I-16 Homework. In this transform function:

Code: Select all

std::transform(
			std::istream_iterator<std::string>( std::istringstream( nambies)),
			std::istream_iterator<std::string>(),
			std::ostream_iterator<int>(std::cout),
			[&numbers](const std::string& word)
			{
				return std::find_if(numbers.begin(), numbers.end(),
					[&word](const Pube& p)
					{
						return p.str == word;
					}
				)->num;
			}
		);
I get the following errors with the first istream_iterator:
  • no instance of constructor "std::istream_iterator<_Ty, _Elem, _Traits, _Diff>::istream_iterator [with _Ty=std::string, _Elem=char, _Traits=std::char_traits<char>, _Diff=ptrdiff_t]" matches the argument list
  • '<function-style-cast>': cannot convert from 'std::istringstream' to 'std::istream_iterator<std::string,char,std::char_traits<char>,ptrdiff_t>'
I followed the code exactly as Chili did and as I understand we are splitting the nambies string into seperate words, converting that to a vector (which seems to be causing the error) and using that as the first argument for the transform function so that we can get the corresponding digit from the 'numbers' vector. I just can't see what I'm doing wrong, as far as I could tell no other header file was added from what was in the start file. Any help would be awesome!
I attached a screenshot of what I am seeing.

Re: Intermediate HW 16 - Problem 2 error with istream_iterator

Posted: May 8th, 2019, 3:52 pm
by Yumtard
try this

Code: Select all

std::istringstream ss( nambies );
		std::transform(
			std::istream_iterator<std::string>( ss ),
			std::istream_iterator<std::string>(),
			std::ostream_iterator<int>( std::cout ),
			[&numbers]( const std::string& word )
according to the documentation, istream_iterator takes a ref to stream, not a const ref

Re: Intermediate HW 16 - Problem 2 error with istream_iterator

Posted: May 8th, 2019, 4:59 pm
by ac11b
Thank you, that works and I see why. I just wonder how the other method worked for Chili in the video lol!