Ind Oubt Ind Oubt - 5 days ago 6
C++ Question

"error: expected constructor, destructor, or type conversion before '(' token" at position of memset invocation

In the above code I'm getting an error with G++ at the memset invocation, saying

error: expected constructor, destructor, or type conversion before '(' token
. What's the possible reason?

#include<iostream>
#include<stdlib.h>
#include<utility>
#include<algorithm>
#include<list>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;

int visited[1000];
memset(visited,0,sizeof(visited));
^ //This is where the error points to.

void dfs(vector< list< pair<int,int> > > graph,int u)
{
visited[u]=1;
cout<<u<<" ";

list< pair<int,int> >::iterator x=graph[u].begin();
for(;x!=graph[u].end();x++)
if(!visited[x->first])
dfs(graph,x->first);
}

int main()
{
int v,e;
cout<<"Vertices,edges?\n";
cin>>v>>e;
vector< list< pair<int,int> > > graph(v+1);
for(int i=1;i<=e;i++)
{
int source,dest,weight;
cin>>source>>dest>>weight;
graph[source].push_back(make_pair(dest,weight));
}
list< pair<int,int> >::iterator p;
int i=1;
while(i<=v)
{
p=graph[i].begin();
for(;p!=graph[i].end();p++)
cout<<i<<" "<<p->first<<" : weight is "<<p->second<<"\n";
i++;
}
dfs(graph,1);cout<<"\n";
return 0;
}


It would also be really helpful if you could provide tips for me to improve my code/coding practice. Thanks!

Answer

std::memset, as is the case for any function, can only be called within a function.

You can't simply call it in "global scope", if you get my meaning. That's what's confusing the compiler.

In your particular case, you don't need the memset call as global variables are zero-initialised in C++.

Consider also replacing #include<stdlib.h> with the C++ header #include <cstdlib>.

Comments