I am attempting to print containers, like sets and maps. The book I am using says the following code is valid:
#include <iostream>
#include <set>
#include <iterator>
#include <fstream>
using namespace std;
template <typename Container>
void print (const Container & c, ostream & out = cout)
{
typename Container::const_iterator itr;
for( itr=c.begin(); itr!=c.end(); ++itr)
out << *itr << " ";
out << endl;
}
int main()
{
ifstream fin("Test.txt");
set<string> s( istream_iterator<string>(fin),
istream_iterator<string>() );
print( s );
return 0;
}
Yet I am getting the an error from Visual Studio's compiler. What am I missing? I know it is likely something simple like an include yet I am unfamiliar with STL Containers and C++ iterators.
I already have #include <iterator>
Errors:
'Container': must be a class or namespace when followed by '::'
'itr' : undeclared identifier
'const_iterator' : is not a member of '`global namespace''
and a few more I am sure are a result of the first one.
Edit:
Per the textbook, the following code should be equivalent to that in my main. I could not get it to work but it may help:
ifstream fin("Test.txt");
string x;
set<string> s;
while( fin >> x)
s.insert(x);
Edit:
Visual Studio build output:
------ Build started: Project: project, Configuration: Debug Win32 ------
Build started 4/15/2012 1:19:25 PM.
InitializeBuildStatus:
Touching "Debug\project.unsuccessfulbuild".
ClCompile:
Project4.cpp
c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(11): error C2825: 'Container': must be a class or namespace when followed by '::'
c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(22) : see reference to function template instantiation 'void print<std::set<_Kty>
(std::istream_iterator<_Ty>,std::istream_iterator<_Ty> (__cdecl *)(void))>(Container (__cdecl &),std::ostream &)' being compiled
with
[
_Kty=std::string,
_Ty=std::string,
Container=std::set<std::string> (std::istream_iterator<std::string>,std::istream_iterator<std::string> (__cdecl *)(void))
]
c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(11): error C2039: 'const_iterator' : is not a member of '`global namespace''
c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(11): error C2146: syntax error : missing ';' before identifier 'itr'
c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(11): error C2065: 'itr' : undeclared identifier
c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(12): error C2065: 'itr' : undeclared identifier
c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(12): error C2228: left of '.begin' must have class/struct/union
type is 'std::set<_Kty> (__cdecl &)'
with
[
_Kty=std::string
]
c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(12): error C2065: 'itr' : undeclared identifier
c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(12): error C2228: left of '.end' must have class/struct/union
type is 'std::set<_Kty> (__cdecl &)'
with
[
_Kty=std::string
]
c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(12): error C2065: 'itr' : undeclared identifier
c:\users\admin\documents\visual studio 2010\projects\project\project\project4.cpp(13): error C2065: 'itr' : undeclared identifier
Build FAILED.
Time Elapsed 00:00:01.00
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
It thinks this is a function declaration:
set<string> s( istream_iterator<string>(fin),
istream_iterator<string>() );
Adding an extra pair of parentheses will correct it:
set<string> s( (istream_iterator<string>(fin)),
istream_iterator<string>() );
There are many examples of this on SO if you search for Most Vexing Parse.
Edit: You also need to add #include <string>
Seems like the compilers (also clang++) seem to get confused. The following works for me, though:
#include <iostream>
#include <set>
#include <iterator>
#include <fstream>
using namespace std;
template <typename Container>
void print (const Container & c, ostream & out = cout)
{
typename Container::const_iterator itr;
for( itr=c.begin(); itr!=c.end(); ++itr)
out << *itr << " ";
out << endl;
}
int main()
{
ifstream fin("Test.txt");
istream_iterator<string> first(fin), last;
set<string> s(first, last);
print(s);
return 0;
}
However, I would recommend turning your print function into something which accepts an iterator range which which you output using std::copy, as is shown here: http://www.sgi.com/tech/stl/ostream_iterator.html
Related
This question already has answers here:
error C2065: 'cout' : undeclared identifier
(26 answers)
Closed 6 years ago.
So i'm trying to run this in Visual Studio but it gives me several errors in the output console:
1>------ Build started: Project: ConsoleApplication1, Configuration: Release x64 ------
1> stdafx.cpp
1> ConsoleApplication1.cpp
1>ConsoleApplication1.cpp(6): error C2039: 'cout': is not a member of 'std'
1> predefined C++ types (compiler internal)(209): note: see declaration of 'std'
1>ConsoleApplication1.cpp(6): error C2065: 'cout': undeclared identifier
1>ConsoleApplication1.cpp(6): warning C4554: '<<': check operator precedence for possible error; use parentheses to clarify precedence
1>ConsoleApplication1.cpp(6): error C2039: 'endl': is not a member of 'std'
1> predefined C++ types (compiler internal)(209): note: see declaration of 'std'
1>ConsoleApplication1.cpp(6): error C2065: 'endl': undeclared identifier
My code is as follows:
#include <iostream>
#include "stdafx.h"
void test(int x, int y)
{
std::cout << x + y << std::endl;
}
int main()
{
test(1, 2);
return 0;
}
You didn't read the documentation for the program you're using.
#include "stdafx.h" must come first.
Change the order of the header file inclusions. The precompiled header inclusion must always be the first non-comment in your source files.
Well, I successfully built the test programme:
#include <boost/lambda/lambda.hpp>
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
using namespace boost::lambda;
typedef std::istream_iterator<int> in;
std::for_each(
in(std::cin), in(), std::cout << (_1 * 3) << " " );
}
but when I tried the one for boost::mpl::map, it barfed:
#include <boost/mpl/map.hpp>
#include <boost/mpl/assert.hpp>
int main()
{
using std::is_same;
using boost::mpl::at;
using boost::mpl::long_;
using boost::mpl::void_;
using boost::mpl::map;
using boost::mpl::pair;
//using namespace boost::mpl;
typedef map <
pair<int, unsigned>
, pair<char, unsigned char>
, pair<long_<5>, char[17]>
, pair < int[42], bool >
> m;
BOOST_MPL_ASSERT_RELATION(size<m>::value, == , 4);
BOOST_MPL_ASSERT_NOT((empty<m>));
BOOST_MPL_ASSERT((is_same< at<m, int>::type, unsigned >));
BOOST_MPL_ASSERT((is_same< at<m, long_<5> >::type, char[17] >));
BOOST_MPL_ASSERT((is_same< at<m, int[42]>::type, bool >));
BOOST_MPL_ASSERT((is_same< at<m, long>::type, void_ >));
return 0;
}
This is the compiler output:
1>------ Build started: Project: example, Configuration: Debug Win32 ------
1> example.cpp
1>c:\projects\example\example\example.cpp(22): error C2027: use of undefined type 'boost::mpl::size<m>'
1>c:\projects\example\example\example.cpp(22): error C2065: 'value' : undeclared identifier
1>c:\projects\example\example\example.cpp(22): error C2975: 'x' : invalid template argument for 'boost::mpl::assert_relation', expected compile-time constant expression
1> c:\boost_1_57_0\boost\mpl\assert.hpp(120) : see declaration of 'x'
1>c:\projects\example\example\example.cpp(22): error C2664: 'int boost::mpl::assertion_failed<0>(boost::mpl::assert<false>::type)' : cannot convert argument 1 from 'boost::mpl::failed ************boost::mpl::assert_relation<0,4,bool boost::mpl::operator ==(boost::mpl::failed,boost::mpl::failed)>::* ***********' to 'boost::mpl::assert<false>::type'
1> No constructor could take the source type, or constructor overload resolution was ambiguous
1>c:\boost_1_57_0\boost\mpl\assert.hpp(176): error C2027: use of undefined type 'boost::mpl::empty<m>'
1> c:\projects\example\example\example.cpp(23) : see reference to class template instantiation 'boost::mpl::assert_arg_pred<boost::mpl::empty<m>>' being compiled
1>c:\boost_1_57_0\boost\mpl\assert.hpp(176): error C2146: syntax error : missing ';' before identifier 'p_type'
1>c:\boost_1_57_0\boost\mpl\assert.hpp(176): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\boost_1_57_0\boost\mpl\assert.hpp(177): error C2653: 'p_type' : is not a class or namespace name
1>c:\boost_1_57_0\boost\mpl\assert.hpp(177): error C2065: 'value' : undeclared identifier
1>c:\boost_1_57_0\boost\mpl\assert.hpp(177): error C2975: 'unnamed-parameter' : invalid template argument for 'boost::mpl::assert_arg_pred_impl', expected compile-time constant expression
1> c:\boost_1_57_0\boost\mpl\assert.hpp(171) : see declaration of 'unnamed-parameter'
1>c:\boost_1_57_0\boost\mpl\assert.hpp(182): error C2027: use of undefined type 'boost::mpl::empty<m>'
1> c:\projects\example\example\example.cpp(23) : see reference to class template instantiation 'boost::mpl::assert_arg_pred_not<boost::mpl::empty<m>>' being compiled
1>c:\boost_1_57_0\boost\mpl\assert.hpp(182): error C2146: syntax error : missing ';' before identifier 'p_type'
1>c:\boost_1_57_0\boost\mpl\assert.hpp(182): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\boost_1_57_0\boost\mpl\assert.hpp(183): error C2653: 'p_type' : is not a class or namespace name
1>c:\boost_1_57_0\boost\mpl\assert.hpp(183): error C2065: 'value' : undeclared identifier
1>c:\boost_1_57_0\boost\mpl\assert.hpp(183): error C2057: expected constant expression
1>c:\boost_1_57_0\boost\mpl\assert.hpp(184): error C2975: 'unnamed-parameter' : invalid template argument for 'boost::mpl::assert_arg_pred_impl', expected compile-time constant expression
1> c:\boost_1_57_0\boost\mpl\assert.hpp(171) : see declaration of 'unnamed-parameter'
1>c:\projects\example\example\example.cpp(23): error C2668: 'boost::mpl::assert_not_arg' : ambiguous call to overloaded function
1> c:\boost_1_57_0\boost\mpl\assert.hpp(203): could be 'boost::mpl::assert<false> boost::mpl::assert_not_arg<boost::mpl::empty<m>>(void (__cdecl *)(Pred),int)'
1> with
1> [
1> Pred=boost::mpl::empty<m>
1> ]
1> c:\boost_1_57_0\boost\mpl\assert.hpp(194): or 'boost::mpl::failed ************boost::mpl::not_<boost::mpl::empty<m>>::* ***********boost::mpl::assert_not_arg<boost::mpl::empty<m>>(void (__cdecl *)(Pred),int)'
1> with
1> [
1> Pred=boost::mpl::empty<m>
1> ]
1> while trying to match the argument list '(void (__cdecl *)(boost::mpl::empty<m>), int)'
1>c:\projects\example\example\example.cpp(25): fatal error C1903: unable to recover from previous error(s); stopping compilation
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Even doing the following:
#include <boost/mpl/map.hpp>
int main()
{
using std::is_same;
using boost::mpl::at;
using boost::mpl::long_;
using boost::mpl::map;
using boost::mpl::pair;
typedef map <
pair<int, unsigned>
, pair<char, unsigned char>
, pair<long_<5>, char[17]>
, pair < int[42], bool >
> m;
at<m, int>::type a;
return 0;
}
fails:
1>------ Build started: Project: example, Configuration: Debug Win32 ------
1> example.cpp
1>c:\projects\example\example\example.cpp(18): error C2027: use of undefined type 'boost::mpl::at<m,int>'
1>c:\projects\example\example\example.cpp(18): error C2065: 'type' : undeclared identifier
1>c:\projects\example\example\example.cpp(18): error C2146: syntax error : missing ';' before identifier 'a'
1>c:\projects\example\example\example.cpp(18): error C2065: 'a' : undeclared identifier
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
I've installed VS Community 2013 Update 4. Am I using this incorrectly or is this a failure with the version I've installed? Release notes for 1.57.0 doesn't reference anything, nor does their bug system.
Basically there's a whole slew of missing headers. The last, simplest, one just misses
#include <boost/mpl/at.hpp>
#include <type_traits>
(that's on GCC, so MSVC might require some more due to implementation defined indirect header includes).
The full map sample needs at least
#include <boost/mpl/assert.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/empty.hpp>
#include <boost/mpl/map.hpp>
#include <boost/mpl/size.hpp>
#include <type_traits>
And some more usings:
using boost::mpl::empty;
using boost::mpl::size;
I have some troubles with the following code
#include<iostream>
#include<iomanip>
#include<fstream>
#include<vector>
#include<stack>
#include<queue>
#include<cstring>
#include<functional>
#include<algorithm>
using namespace std;
struct node
{
int weight;
unsigned char value;
const node * child0;
const node *child1;
node(unsigned char c=0,int i=-1){
value=c;
weight=-1;
child0=0;
child1=0;
}
//construct new internal node that has children c1 and c2
node (const node* c0,const node *c1){
value=0;
weight=c0->weight+c1->weight;
child0=c0;
child1=c1;
}
bool operator<(const node &a) const {
return weight<a.weight;
}
void traverse(char * code=" " ) const;
};
void node::traverse(char * code ) const
{
if(child0)
{
child0->traverse(code +'0');
child1->traverse(code +'1');
}
else
{
cout<<" "<<value <<" ";
cout<<setw(2)<<weight;
cout<<" "<<code<<endl;
}
}
void count_chars(int *counts)
{
for (int i=0;i<256;i++)
counts[i]=0;
//ifstream file( "input.data");
//if(!file){
//cerr<<" couldnt open input file!\n";
//throw "abort";
//file.setf(ios::skipws);
unsigned char c;
while(true)
{
cin>>c;
if(c){
counts[c]++;
}
else
break;
}
}
int main()
{
int counts[256];
count_chars(counts);
priority_queue<vector<node>,greater<node> >q;
for(int i=0;i<256;++i)
if(counts[i])
q.push(node(i,counts[i]));
while(q.size()<1)
{
node *child0=new node(q.top());
q.pop();
node *child1=new node(q.top());
q.pop();
q.push(node(child0,child1));
}
cout<<" char Symbol code "<<endl;
q.top().traverse();
return 0;
}
But it shows me some errors. For example unknown size of priority_queue and so on. Here is also the error list
1>------ Build started: Project: HUffman_coding, Configuration: Debug Win32 ------
1> HUffman_coding.cpp
1>c:\program files\microsoft visual studio 10.0\vc\include\queue(212): error C2039: 'value_type' : is not a member of 'std::greater<_Ty>'
1> with
1> [
1> _Ty=node
1> ]
1>c:\program files\microsoft visual studio 10.0\vc\include\queue(212): error C2146: syntax error : missing ',' before identifier 'value_type'
1>c:\program files\microsoft visual studio 10.0\vc\include\queue(212): error C2065: 'value_type' : undeclared identifier
1>c:\users\daviti\documents\visual studio 2010\projects\huffman_coding\huffman_coding\huffman_coding.cpp(100): error C3203: 'less' : unspecialized class template can't be used as a template argument for template parameter '_Pr', expected a real type
1>c:\users\daviti\documents\visual studio 2010\projects\huffman_coding\huffman_coding\huffman_coding.cpp(100): error C2955: 'std::less' : use of class template requires template argument list
1> c:\program files\microsoft visual studio 10.0\vc\include\xfunctional(121) : see declaration of 'std::less'
1>c:\users\daviti\documents\visual studio 2010\projects\huffman_coding\huffman_coding\huffman_coding.cpp(100): error C2133: 'q' : unknown size
1>c:\users\daviti\documents\visual studio 2010\projects\huffman_coding\huffman_coding\huffman_coding.cpp(100): error C2512: 'std::priority_queue' : no appropriate default constructor available
1>c:\users\daviti\documents\visual studio 2010\projects\huffman_coding\huffman_coding\huffman_coding.cpp(103): error C2663: 'std::priority_queue<_Ty,_Container,_Pr>::push' : 2 overloads have no legal conversion for 'this' pointer
1>c:\users\daviti\documents\visual studio 2010\projects\huffman_coding\huffman_coding\huffman_coding.cpp(104): error C2662: 'std::priority_queue<_Ty,_Container,_Pr>::size' : cannot convert 'this' pointer from 'std::priority_queue' to 'const std::priority_queue<_Ty,_Container,_Pr> &'
1> Reason: cannot convert from 'std::priority_queue' to 'const std::priority_queue<_Ty,_Container,_Pr>'
1> Conversion requires a second user-defined-conversion operator or constructor
1>c:\users\daviti\documents\visual studio 2010\projects\huffman_coding\huffman_coding\huffman_coding.cpp(104): fatal error C1903: unable to recover from previous error(s); stopping compilation
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
I have also recognized that, when I am trying to do like this q.top().traverse() after top. it does not show me traverse option. What is wrong?
I think that instead of
priority_queue<vector<node>,greater<node> >q;
you meant to write:
priority_queue<node, vector<node>, greater<node> >q;
That should solve the errors you're seeing at the moment.
And like I suggested, please do properly format your code. It will make everything so much easier to read and probably makes receiving answers more likely.
I have this code from programming pearls
#include <iostream>
//#include <string>
using namespace std;
template <class T>
void measure(char *text)
{
cout<<"measure"<<text<<"\t";
cout<<sizeof(t)<<"\n";
}
#define MEASURE(T,text){
cout<<text<<"\t";
cout<<sizeof(T)<<"\t";
int lastp=0;
for (int i=0;i<11;i++){
T *p=new T;
int thisp=(int)p;
if (lastp!=0)
cout<<" "<<thisp-lastp;
lastp=thisp;
}
cout<<"n":
}
int main(){
return 0;
}
but there are some mistakes
1>------ Build started: Project: new_practises, Configuration: Debug Win32 ------
1> practises.cpp
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(11): error C2143: syntax error : missing ';' before '<<'
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(11): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(12): error C2143: syntax error : missing ';' before '<<'
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(12): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(12): error C2086: 'int cout' : redefinition
1> c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(11) : see declaration of 'cout'
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(14): error C2059: syntax error : 'for'
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(14): error C2143: syntax error : missing ')' before ';'
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(14): error C2143: syntax error : missing ';' before '<'
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(14): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(14): error C2143: syntax error : missing ';' before '++'
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(14): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(14): error C2086: 'int i' : redefinition
1> c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(14) : see declaration of 'i'
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(14): error C2059: syntax error : ')'
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(14): error C2143: syntax error : missing ';' before '{'
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(14): error C2447: '{' : missing function header (old-style formal list?)
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(21): error C2143: syntax error : missing ';' before '<<'
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(21): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(21): error C2086: 'int cout' : redefinition
1> c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(11) : see declaration of 'cout'
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(22): error C2059: syntax error : '}'
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(22): error C2143: syntax error : missing ';' before '}'
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(22): error C2059: syntax error : '}'
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(24): error C2143: syntax error : missing ';' before '{'
1>c:\users\david\documents\visual studio 2010\projects\new_practises\practises.cpp(24): error C2447: '{' : missing function header (old-style formal list?)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
What do I need to fix?
DeadMG is correct, there are quite a few mistakes here. The most prominent one is that you are not using #define correctly. It requires that all of the code of the function goes on one line.
#define func(A, B) {//function body goes here}
To allow multi-line #defines, use \s at the end of the lines:
#define MEASURE(T,text) {\
cout<<text<<"\t";\
cout<<sizeof(T)<<"\t";\
int lastp=0;\
for (int i=0;i<11;i++){\
T *p=new T;\
int thisp=(int)p;\
if (lastp!=0) cout<<" "<<thisp-lastp;\
lastp=thisp;\
}\
cout<<"n";\
}
(Note I have fixed a few typos here, including one : where a ; should be.)
The other big problem with your code is in the measure function:
void measure(char *text)
{
cout<<"measure"<<text<<"\t";
cout<<sizeof(t)<<"\n";
}
What is t? I assume you mean text, not t.
The following should compile okay.
#include <iostream>
#define MEASURE(T,text) {\
cout<<text<<"\t";\
cout<<sizeof(T)<<"\t";\
int lastp=0;\
for (int i=0;i<11;i++){\
T *p=new T;\
int thisp=(int)p;\
if (lastp!=0) cout<<" "<<thisp-lastp;\
lastp=thisp;\
}\
cout<<"n";\
}
using namespace std;
template <class T>
void measure(char *text)
{
cout<<"measure"<<text<<"\t";
cout<<sizeof(text)<<"\n";
}
int main() {
return 0;
}
As a final, not directly bug-related question to you - why are you using a #define like this? Why not simply write the #define code into the measure method? #defineis usually used to give a short name for a variable or to declare very small functions - and there is a vocal part of the community that thinks they shouldn't be used at all!
In addition to Stephen's answer, I can say that #define is un-C++ish. It becomes useful when you need a variable name that corresponds to a string or something the like. For mostly all other cases, use functions.
Next to that, I must concur with DeadMG's opinion that at least I'm too stupid to see any reason to write this function. But that's another concern :)
If you actually want to measure the length of a string, you can use the function strlen.
What your MEASURE seems to do is print out a series of 11 newly allocated memory addresses. Nice to do when you are studying the memory allocation strategy of your runtime, but otherwise not too useful.
Also don't forget to delete what you have newed.
#define MEASURE(T,text) {\
cout<<text<<"\t";\
cout<<sizeof(T)<<"\t";\
...
can be directly translated into a template function: way easier to write, and to debug.
template< typename T > // assuming you _need_ a variable type of arguments
void MEASURE( const T& text) {
cout<<text<<"\t";
cout<<sizeof(T)<<"\t";
// will write the size of e.g. one character. Maybe
// you should use strlen or the like...
int lastp=0;
for (int i=0;i<11;i++){
T *p=new T;
int thisp=(int)p;
if (lastp!=0) cout<<" "<<thisp-lastp;
lastp=thisp;
}
cout<<"n";
}
"some" mistakes? Whoever wrote that has NFI what on earth they're doing. The program doesn't even produce any meaningful output. ... or any output at all. You could literally not run it or read the source code and gain the same knowledge: zero.
You need to add "\" at the end of the line when your definition across multiple lines.
Below code is compiled with no errors.
#include "stdafx.h"
#include <iostream>
using namespace std;
template <class T>
void measure(char *text)
{
cout<<"measure"<<text<<"\t";
cout<<sizeof(t)<<"\n";
}
#define MEASURE(T,text) { \
cout<<text<<"\t"; \
cout<<sizeof(T)<<"\t"; \
int lastp=0; \
for (int i=0;i<11;i++){ \
T *p=new T; \
int thisp=(int)p; \
if (lastp!=0) \
cout<<" "<<thisp-lastp; \
lastp=thisp; \
} \
cout<<"n": \
}
int main(){
return 0;
}
When I try to use my iterator class
template<class T>
class list
{
public:
class iterator;
};
template<class T>
class list<T>::iterator
{
//stuff
};
as a return type in an operator overloading,
template<class T>
class list<T>::iterator
{
public:
iterator& operator++();
protected:
list* lstptr;
};
template<class T>
iterator& list<T>::iterator::operator++()
{
(this->lstptr)->current = ((this->lstptr)->current)->next;
return this;
}
I get these errors:
s:\jeffrey_\my_freeware_games\o\resources\container class\container(spec- o)\container_def.h(213) : error C2143: syntax error : missing ';' before '&'
s:\jeffrey_\my_freeware_games\o\resources\container class\container(spec- o)\container_def.h(213) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
s:\jeffrey_\my_freeware_games\o\resources\container class\container(spec- o)\container_def.h(213) : error C2065: 'T' : undeclared identifier
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(235) : error C2039: 'Yes' : is not a member of 'vc_attributes'
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(235) : error C2065: 'Yes' : undeclared identifier
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(236) : error C2039: 'No' : is not a member of 'vc_attributes'
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(236) : error C2065: 'No' : undeclared identifier
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(237) : error C2039: 'Maybe' : is not a member of 'vc_attributes'
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(237) : error C2065: 'Maybe' : undeclared identifier
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(240) : error C2039: 'NoAccess' : is not a member of 'vc_attributes'
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(240) : error C2065: 'NoAccess' : undeclared identifier
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(241) : error C2039: 'Read' : is not a member of 'vc_attributes'
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(241) : error C2065: 'Read' : undeclared identifier
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(242) : error C2039: 'Write' : is not a member of 'vc_attributes'
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(242) : error C2065: 'Write' : undeclared identifier
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(243) : error C2039: 'ReadWrite' : is not a member of 'vc_attributes'
c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h(243) : error C2065: 'ReadWrite' : undeclared identifier
c:\program files\microsoft visual studio 9.0\vc\include\crtdefs.h(582) : error C2146: syntax error : missing ';' before identifier 'time_t'
c:\program files\microsoft visual studio 9.0\vc\include\crtdefs.h(2047) : error C2143: syntax error : missing ';' before 'identifier'
c:\program files\microsoft visual studio 9.0\vc\include\crtdefs.h(2047) : warning C4091: 'typedef ' : ignored on left of 'localeinfo_struct' when no variable is declared
c:\program files\microsoft visual studio 9.0\vc\include\crtdefs.h(2047) : fatal error C1075: end of file found before the left brace '{' at 'c:\program files\microsoft visual studio 9.0\vc\include\crtdefs.h(174)' was matched
NB: container_def.h is the header file for my list and iterator classes, I have no idea what souceannotations or crtdefs are.
iterator is not yet known at that point. You need to tell it it's in the list<T> class:
template<class T>
typename list<T>::iterator& list<T>::iterator::operator++() {
(this->lstptr)->current = ((this->lstptr)->current)->next;
return *this; // *this here, since this is a pointer only
}
Notice the typename is required, since list<T>::iterator is a type prefixed with a template specialization, and you need to tell the compiler about that - in spite of the fact that Visual C++ probably will accept code not putting typename before it. Omitting the typename, the compiler should assume it's not a type and should sort of produce the same error message.
You could safe yourself that hassle by putting the code straight into the class:
template<class T>
class list<T>::iterator
{
public:
iterator& operator++() {
(this->lstptr)->current = ((this->lstptr)->current)->next;
return *this; // *this here, since this is a pointer only
}
protected:
list* lstptr;
};
litb has answered your question completely. I think it worth highlighting that in an effort to make C++ easier to use, the C++ Committee has added a new syntax for the declaration of functions. The result is that you'll be able to define your function as follows (n2541) without needing the extra qualification:
template<class T>
auto list<T>::iterator::operator++()->iterator&
{
// ...
}
According to the supported feature list, GCC 4.4 already has this feature.