stl copy

Started by
3 comments, last by guyaton 18 years, 8 months ago
In stl I know that this is legal:

vector<int> someVec;
copy( someVec.begin(), someVec.end(), ostream_iterator<int>( cout, ", " ) );

but how do I do it if vector is of a class. Here's my example that I am trying to do (in this case I am trying to write to a file as well).

class SVariables
{
public:
	string strVariableName;
	unsigned long ulLineNumber;

	SVariables()
	{
		strVariableName = "";
		ulLineNumber = 0L;
	}

};

vector<SVariables> g_Variables;

how do I output this to a file? This is the error that I am getting: c:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\include\iterator(257): error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const SVariables' (or there is no acceptable conversion) thanks for your help in advace. ~guyaton
~guyaton
Advertisement
You need to overload the stream extraction operator (<<) for user-defined types for things like std::ostream_iterator, e.g:

#include <ostream>template < typename CharT, typename Traits >inline std::basic_ostream<CharT, Traits>&operator<<(std::basic_ostream<CharT, Traits>& out, const SVariables& sv) {   return out << "name: " << vs.strVariableName << ", line num: " << sv.ulLineNumber;}//.....vector<SVariables> someVec;std::copy(someVec.begin(), someVec.end(),          std::ostream_iterator<SVariables>(std::cout, "\n"));
now i am getting this error.

c:\programming\compare\compare\compare.cpp(45): error C2804: binary 'operator <<' has too many parameters

here is the source:

class SVariables{public:	string strVariableName;	unsigned long ulLineNumber;	//unsigned long ulBracket;	SVariables()	{		strVariableName = "";		ulLineNumber = 0L;		//ulBracket = 0L;	}	template < typename CharT, typename Traits >	inline std::basic_ofstream<CharT, Traits>&	operator<<(std::basic_ofstream<CharT, Traits>& out, const SVariables& sv) 	{		return out << "name: " << vs.strVariableName << ", line num: " << sv.ulLineNumber;	}//this is line number 45 that the error is on.};
~guyaton
operator<<(std::basic_ofstream<CharT, Traits>& out, const SVariables& sv) should not be a member function of SVariables, but an ordinary non-member function.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
that worked, thnx

~guyaton
~guyaton

This topic is closed to new replies.

Advertisement