Including any new header makes the project give irrelevant errors - c++

Im working on an open-source project "powder toy" and manged to compile it under msvc. Run fine. But when I include a new header in air.h, compiling gives errors such as:
'GetUserNameA! is not a member of 'SaveInfo' in GameController.cpp file.
and
syntax error: '::' in BitmapBrush.h file. ---> pointing min - max of windows.
Both files are untouched and does not have anything in common with the header I added:
Aux_cl.h ---> added to beginning of air.h
this header has just opencl headers which powdertoy does not have them in any of other cpp/h files.
What am I doing wrong?
If I delete the inclusion of Aux_cl, project compiles fine even with the opencl bindings in the Aux_cl(this not bind to anything, just compiled separately I think)
Edit: When I add "#undef min" and "#undef GetUserName" before those error points, it compiles file, I wonder how it works without my header files included before.
Edit2: Should I add #def blabla just after the functions after those #undef blabla ?
Here is the
Air.h:
#ifndef AIR_H
#define AIR_H
#include "Config.h"
#include "Aux_cl.h"
class Simulation;
class Air
{
public:
Simulation & sim;
int airMode;
float ambientAirTemp;
Aux_cl *gpu;
//Arrays from the simulation
unsigned char (*bmap)[XRES/CELL];
unsigned char (*emap)[XRES/CELL];
float (*fvx)[XRES/CELL];
float (*fvy)[XRES/CELL];
//
float vx[YRES/CELL][XRES/CELL];
float ovx[YRES/CELL][XRES/CELL];
float vy[YRES/CELL][XRES/CELL];
float ovy[YRES/CELL][XRES/CELL];
float pv[YRES/CELL][XRES/CELL];
float opv[YRES/CELL][XRES/CELL];
float hv[YRES/CELL][XRES/CELL];
float ohv[YRES/CELL][XRES/CELL]; // Ambient Heat
unsigned char bmap_blockair[YRES/CELL][XRES/CELL];
unsigned char bmap_blockairh[YRES/CELL][XRES/CELL];
float kernel[9];
void make_kernel(void);
void update_airh(void);
void update_air(void);
void Clear();
void ClearAirH();
void Invert();
Air(Simulation & sim);
};
#endif
Aux_cl.h:
#pragma once
#define __CL_ENABLE_EXCEPTIONS
#include<CL\opencl.h>
#include<CL\cl.hpp>
#include<CL\cl.h>
#include"ClKernelFactory.h" // this has nothing but string variables and simple function. No other includes about windows or powder toy
#define FIRST_COMPUTE_DEVICE 0
/*
Simple compute helper class for your heavy work loads.
Uses OpenCL 1.2 headers so you may need an up-to-date CPU or an AMD-GPU for now.
Instances of this classes are different contexts and should be compiled serially.
Computation can be concurrent without fear.
Writer: Huseyin Tugrul BUYUKISIK
*/
class Aux_cl
{
public:
cl::Context *context;
std::vector<cl::Program::Sources> sources;
std::vector<cl::Program> programs;
std::vector<std::vector<cl::Device>> devicesCPU;
std::vector<std::vector<cl::Device>> devicesGPU;
cl::CommandQueue cq;
std::vector<cl::Buffer> buffers;
std::vector<cl::Memory> memories;
std::vector<cl::NDRange> globalRanges;
std::vector<cl::NDRange> localRanges;
std::vector<cl::NDRange> referenceRanges;
std::vector<std::string> kernelFunctionsToBeCompiled;
std::vector<std::string> kernelNames;
std::vector<std::string> bufferNames;
std::vector<cl::Kernel> kernelFunctions;
std::vector<std::pair<std::vector<int>,int>> bufferTargetsForKernels; // {500}, {501, 502},{530} ... --> buffer ids
// 0,1,2,... --> kernel ids
std::vector<std::pair<int,std::vector<std::string>>> bufferDefinitions;
std::vector<std::pair<int,std::string>> kernelDefinitions;
std::vector<cl::Platform> platforms;
cl_context_properties *context_properties;
std::string CPU_GPU; //"gpu" "GPU" "graphics" "GRAPHICS" "cpu" "CPU"
int kernelId;
int bufferId;
int numberOfCPU;
int numberOfGPU;
int first_CPU_platform;
int first_CPU_device;
int first_GPU_platform;
int first_GPU_device;
int second_CPU_platform;
int second_CPU_device;
int second_GPU_platform;
int second_GPU_device;
int which_one;
static const int FIRST=0, SECOND=1, THIRD=2, FOURTH=3, OMG=4;
Aux_cl(std::string gpu_or_cpu, int whichOne)
{
which_one=whichOne;
CPU_GPU=gpu_or_cpu;
kernelId=0;
bufferId=0;
numberOfGPU=0;
numberOfCPU=0;
cl::Platform::get(&platforms);
for(int i=0;i<platforms.size();i++)
{
devicesCPU.push_back(std::vector<cl::Device>()); // one device list for each platform (AMD, NVIDIA, INTEL, ...)
}
for(int i=0;i<platforms.size();i++)
{
devicesGPU.push_back(std::vector<cl::Device>()); // one device list for each platform (AMD, NVIDIA, INTEL, ...)
}
//selecting the platform that has a cpu or gpu specified in construction
for(int i=0;i<platforms.size();i++)
{
platforms[i].getDevices(CL_DEVICE_TYPE_CPU,&devicesCPU[i]);
}
//selecting the platform that has a cpu or gpu specified in construction
for(int i=0;i<platforms.size();i++)
{
platforms[i].getDevices(CL_DEVICE_TYPE_GPU,&devicesGPU[i]);
}
//searching device lists for a gpu or cpu (as selected in construction)
for(int i=0;i<platforms.size();i++)
{
bool notFoundYet=true;
bool notFoundYet2=true;
if(devicesCPU[i].size()>0)
for(int j=0;j<devicesCPU[i].size();j++)
{
if(notFoundYet)
{
first_CPU_platform=i;
first_CPU_device=j;
notFoundYet=false;
}
if((!notFoundYet)&&(notFoundYet2))
{
second_CPU_platform=i;
second_CPU_device=j;
notFoundYet2=false;
}
numberOfCPU++;
}
}
//searching device lists for a gpu or cpu (as selected in construction)
for(int i=0;i<platforms.size();i++)
{
bool notFoundYet=true;bool notFoundYet2=true;
if(devicesGPU[i].size()>0)
for(int j=0;j<devicesCPU[i].size();j++)
{
if(notFoundYet)
{
first_GPU_platform=i;
first_GPU_device=j;
notFoundYet=false;
}
if((!notFoundYet)&&(notFoundYet2))
{
second_CPU_platform=i;
second_CPU_device=j;
notFoundYet2=false;
}
numberOfGPU++;
}
}
};
void AddKernelFromFactory(KernelIngredients ki)
{
AddKernelToPool(ki.bodyOfKernel, ki.nameOfKernel,
ki.globalX,ki.globalY,
ki.localX,ki.localY);
}
void AddKernelToPool(std::string KernelItself, std::string KernelName,
int GlobalRangeX,int GlobalRangeY,
int LocalRangeX,int LocalRangeY)
{
if(GlobalRangeY!=0)
{
kernelFunctionsToBeCompiled.push_back(KernelItself);
kernelNames.push_back(KernelName);
globalRanges.push_back(cl::NDRange(GlobalRangeX,GlobalRangeY));
localRanges.push_back(cl::NDRange(LocalRangeX,LocalRangeY));
referenceRanges.push_back(cl::NDRange(0,0));
kernelDefinitions.push_back(std::pair<int,std::string>(kernelId,KernelName));
kernelId++;
}
else
{
kernelFunctionsToBeCompiled.push_back(KernelItself);
kernelNames.push_back(KernelName);
globalRanges.push_back(cl::NDRange(GlobalRangeX));
localRanges.push_back(cl::NDRange(LocalRangeX));
referenceRanges.push_back(cl::NDRange(0));
kernelDefinitions.push_back(std::pair<int,std::string>(kernelId,KernelName));
kernelId++;
}
};
void AddBufferToPool(std::string nameOfBuffer,std::string typeOfBuffer, int sizeOfBuffer)
{
// 0,{"a","float","8192"}
std::vector<std::string> BufferNameTypeSize;
BufferNameTypeSize.push_back(nameOfBuffer);
BufferNameTypeSize.push_back(typeOfBuffer);
BufferNameTypeSize.push_back(std::to_string(sizeOfBuffer));
bufferDefinitions.push_back(std::pair<int,std::vector<std::string>>(bufferId,BufferNameTypeSize));
bufferNames.push_back(BufferNameTypeSize[0]);
bufferId++;
}
void WireBuffersToSingleKernel(std::vector<std::string> buffers, std::string theKernel )
{
std::vector<int> bufferL;
int index=-1;
for(int i=0;i<buffers.size();i++)
{
for(int j=0;j<bufferDefinitions.size();j++)
{
if(bufferDefinitions[j].second[0]==(buffers[i]))
{
bufferL.push_back(bufferDefinitions[j].first);
}
}
for(int k=0;k<kernelDefinitions.size();k++)
{
if(kernelDefinitions[k].second==(theKernel))
{
index=kernelDefinitions[k].first;
}
}
}
bufferTargetsForKernels.push_back(std::pair<std::vector<int>,int>(bufferL,index));
// buffers {23,33,10,1,40} for the kernel {3} as a pair
}
void compile()
{
if(which_one==FIRST)
{
//clGetPlatformIDs(1,&platform_id,NULL);
if((CPU_GPU==("CPU"))||(CPU_GPU==("cpu")))
{
cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[first_CPU_platform])(), 0};
context=new cl::Context(CL_DEVICE_TYPE_CPU, properties);
}
if((CPU_GPU==("GPU"))||(CPU_GPU==("gpu")))
{
cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[first_GPU_platform])(), 0};
context=new cl::Context(CL_DEVICE_TYPE_GPU, properties);
}
}
if(which_one==SECOND)
{
//clGetPlatformIDs(1,&platform_id,NULL);
if((CPU_GPU==("CPU"))||(CPU_GPU==("cpu")))
{
cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[second_CPU_platform])(), 0};
context=new cl::Context(CL_DEVICE_TYPE_CPU, properties);
}
if((CPU_GPU==("GPU"))||(CPU_GPU==("gpu")))
{
cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[second_GPU_platform])(), 0};
context=new cl::Context(CL_DEVICE_TYPE_GPU, properties);
}
}
/*
for(int i=0;i<platforms.size();i++)
{
devices[i]=context[0].getInfo<CL_CONTEXT_DEVICES>(); // device lists are created
}
*/
if(which_one==FIRST)
{
for(int i=0;i<kernelFunctionsToBeCompiled.size();i++)
{
sources.push_back(cl::Program::Sources());
sources[i].push_back(std::make_pair(kernelFunctionsToBeCompiled[i].data(),kernelFunctionsToBeCompiled[i].length()));
programs.push_back(cl::Program(context[0],sources[i]));
if((CPU_GPU==("CPU"))||(CPU_GPU==("cpu")))
{
programs[i].build(devicesCPU[first_CPU_platform]);
}
if((CPU_GPU==("GPU"))||(CPU_GPU==("gpu")))
{
programs[i].build(devicesGPU[first_GPU_platform]);
}
kernelFunctions.push_back(cl::Kernel(programs[i],kernelNames[i].data()));
}
if((CPU_GPU==("CPU"))||(CPU_GPU==("cpu")))
{
cq=cl::CommandQueue(context[0],devicesCPU[first_CPU_platform][first_CPU_device]);
}
if((CPU_GPU==("GPU"))||(CPU_GPU==("gpu")))
{
cq=cl::CommandQueue(context[0],devicesGPU[first_GPU_platform][first_GPU_device]);
}
}
if(which_one==SECOND)
{
for(int i=0;i<kernelFunctionsToBeCompiled.size();i++)
{
sources.push_back(cl::Program::Sources());
sources[i].push_back(std::make_pair(kernelFunctionsToBeCompiled[i].data(),kernelFunctionsToBeCompiled[i].length()));
programs.push_back(cl::Program(context[0],sources[i]));
if((CPU_GPU==("CPU"))||(CPU_GPU==("cpu")))
{
programs[i].build(devicesCPU[second_CPU_platform]);
}
if((CPU_GPU==("GPU"))||(CPU_GPU==("gpu")))
{
programs[i].build(devicesGPU[second_GPU_platform]);
}
kernelFunctions.push_back(cl::Kernel(programs[i],kernelNames[i].data()));
}
if((CPU_GPU==("CPU"))||(CPU_GPU==("cpu")))
{
cq=cl::CommandQueue(context[0],devicesCPU[second_CPU_platform][second_CPU_device]);
}
if((CPU_GPU==("GPU"))||(CPU_GPU==("gpu")))
{
cq=cl::CommandQueue(context[0],devicesGPU[second_GPU_platform][second_GPU_device]);
}
}
for(int i=0;i<bufferDefinitions.size();i++)
{
int sizeOfBuffer=std::stoi(bufferDefinitions[i].second[2]);
if(bufferDefinitions[i].second[1]=="float")
{
buffers.push_back(cl::Buffer(context[0],CL_MEM_READ_WRITE,sizeof(cl_float)*sizeOfBuffer));
}
if(bufferDefinitions[i].second[1]=="int")
{
buffers.push_back(cl::Buffer(context[0],CL_MEM_READ_WRITE,sizeof(cl_int)*sizeOfBuffer));
}
if(bufferDefinitions[i].second[1]=="double")
{
buffers.push_back(cl::Buffer(context[0],CL_MEM_READ_WRITE,sizeof(cl_double)*sizeOfBuffer));
}
if(bufferDefinitions[i].second[1]=="long")
{
buffers.push_back(cl::Buffer(context[0],CL_MEM_READ_WRITE,sizeof(cl_long)*sizeOfBuffer));
}
if(bufferDefinitions[i].second[1]=="char")
{
buffers.push_back(cl::Buffer(context[0],CL_MEM_READ_WRITE,sizeof(cl_char)*sizeOfBuffer));
}
}
for(int i=0;i<bufferTargetsForKernels.size();i++)
{
for(int j=0;j<bufferTargetsForKernels[i].first.size();j++)
{
kernelFunctions[bufferTargetsForKernels[i].second].setArg(j,buffers[bufferTargetsForKernels[i].first[j]]);
}
}
}
void SelectClBuffersToWriteOnThem()
{
}
void SelectClBuffersToReadFromThem()
{
}
void WriteToClFromCPP(std::string clArrayName,float *arrayCPP)
{
for(int i=0;i<buffers.size();i++)
{
if(bufferNames[i]==clArrayName)
{
cq.finish();
cq.enqueueWriteBuffer(buffers[i],CL_TRUE,0,sizeof(cl_float)*(std::atoi(bufferDefinitions[i].second[2].data())),arrayCPP);
cq.finish();
}
}
}
void WriteToClFrom2DCPP(std::string clArrayName,static float *arrayCPP) // 2D array = contiguous?
{
for(int i=0;i<buffers.size();i++)
{
if(bufferNames[i]==clArrayName)
{
cq.finish();
cq.enqueueWriteBuffer(buffers[i],CL_TRUE,0,sizeof(cl_float)*(std::atoi(bufferDefinitions[i].second[2].data())), arrayCPP);
cq.finish();
}
}
}
void WriteToClFrom2DCPP(std::string clArrayName,static char *arrayCPP) // 2D array = contiguous?
{
for(int i=0;i<buffers.size();i++)
{
if(bufferNames[i]==clArrayName)
{
cq.finish();
cq.enqueueWriteBuffer(buffers[i],CL_TRUE,0,sizeof(cl_char)*(std::atoi(bufferDefinitions[i].second[2].data())), arrayCPP);
cq.finish();
}
}
}
void ReadFromClToCPP(std::string clArrayName, float *arrayCPP)
{
for(int i=0;i<buffers.size();i++)
{
if(bufferNames[i]==clArrayName)
{
cq.finish();
cq.enqueueReadBuffer(buffers[i],CL_TRUE,0,sizeof(cl_float)*(std::atoi(bufferDefinitions[i].second[2].data())),arrayCPP);
cq.finish();
}
}
}
void ReadFromClTo2DCPP(std::string clArrayName,static float *arrayCPP) // 2D arrays are contiguous?
{
for(int i=0;i<buffers.size();i++)
{
if(bufferNames[i]==clArrayName)
{
cq.finish();
cq.enqueueReadBuffer(buffers[i],CL_TRUE,0,sizeof(cl_float)*(std::atoi(bufferDefinitions[i].second[2].data())), arrayCPP);
cq.finish();
}
}
}
void ReadFromClTo2DCPP(std::string clArrayName,static char *arrayCPP) // 2D arrays are contiguous?
{
for(int i=0;i<buffers.size();i++)
{
if(bufferNames[i]==clArrayName)
{
cq.finish();
cq.enqueueReadBuffer(buffers[i],CL_TRUE,0,sizeof(cl_char)*(std::atoi(bufferDefinitions[i].second[2].data())), arrayCPP);
cq.finish();
}
}
}
std::vector<int> computeList;
void MakeKernelListToRun(std::vector<std::string> listOfKernels)
{
computeList.clear();
for(int j=0;j<listOfKernels.size();j++)
{
for(int i=0;i<kernelNames.size();i++)
{
if(listOfKernels[j]==kernelNames[i])
{
computeList.push_back(i);
}
}
}
}
void ComputeList()
{
for(int i=0;i<computeList.size();i++)
{
cq.enqueueNDRangeKernel(kernelFunctions[computeList[i]],referenceRanges[computeList[i]],globalRanges[computeList[i]],localRanges[computeList[i]]);
}
}
void Compute(std::string kernelName)
{
for(int i=0;i<kernelNames.size();i++)
{
if(kernelName==kernelNames[i])
{
cq.enqueueNDRangeKernel(kernelFunctions[i],referenceRanges[i],globalRanges[i],localRanges[i]);
}
}
}
void releaseClResources()
{
cq.finish();
// opencl c++ bindings wrapper deletes / releases automatically when of no use
}
~Aux_cl(void)
{
delete context;
};
};
Last edit:
In KernelIngredients.cpp there is only #include "KernelIngredients.h"
In KernelIngredients.h there is no inclusion
In ClKernelFactory.h there is only #include "KernelIngredients.h"
In ClKernelFactory.cpp there is only #include "ClKernelFactory.h"
In Aux_cl.cpp there is only #include "Aux_cl.h"
In Aux_cl.h there is only opencl inclusions (i wish these dont use the windows things that clashes with min() and GetUserName() :S )
In Air.h there are #include "Aux_cl.h" and #include"ClKernelFactory.h"

Looks like one of the headers included indirectly via air.h is defining a macro which conflicts with a symbol name elsewhere in the sources. The macro basically defines a search-replace operation which is carried out by the preprocessor, before the compiler kicks in.
Take this example:
/** header_1.h **/
void foo(){ std::cout << "Hello" << std::endl; }
/** header_2.h **/
#define foo bar
/** main.cpp **/
#include "header_1.h"
#include "header_2.h"
int main() {
foo();
}
Compiling main.cpp will give you an error that the method bar is not defined, since the preprocessor replaced all occurrences of foo appearing after the point header_2.hwas included with bar.

Related

In C/C++, I am trying to call different functions (explained in description) in a for loop without if-else ladder

I have some APIs defined like following prototype.
void foo_network_call_1();
void foo_network_call_2();
void foo_network_call_3();
void foo_network_call_4();
and
void foo_parse_data_1();
void foo_parse_data_2();
void foo_parse_data_3();
void foo_parse_data_4();
I can make 4 calls to each type of API to get the work done. That code will not be clean etc.
I am looking for a way to call above APIs in a loop, e.g.for loop.
something like:
for (int i=1; i<5; ++i) {
foo_network_call_##i();
foo_parse_data_##i();
}
##
are just representing that I am appending i in the call. I am not aware of any calling mechanism in C/C++ which can do this.
Thank you your help.
Using an array of function pointers seems like the obvious thing to do.
typedef void (*network_func)();
typedef void (*parse_func)();
network_func network_functions[4] = { foo_network_call_1, ... };
parse_func parse_functions[4] = { foo_parse_data_1, ... };
for (int i = 0; i < 4; ++i)
{
(network_functions[i])();
(parse_functions[i])();
}
#include <iostream>
#include <vector>
using namespace std;
int main()
{
cout << "Hello World!" << endl;
auto foo_network_call_0 = [](){
//do something...
};
auto foo_network_call_1 = [](){
//do something...
};
auto foo_network_call_2 = [](){
//do something...
};
auto foo_network_call_3 = [](){
//do something...
};
auto foo_parse_data_0 = [](){
//do something...
};
auto foo_parse_data_1 = [](){
//do something...
};
auto foo_parse_data_2 = [](){
//do something...
};
auto foo_parse_data_3 = [](){
//do something...
};
std::vector<void(*)()> ary_call;
ary_call.push_back( foo_network_call_0 );
ary_call.push_back( foo_network_call_1 );
ary_call.push_back( foo_network_call_2 );
ary_call.push_back( foo_network_call_3 );
std::vector<void(*)()> ary_data;
ary_data.push_back( foo_parse_data_0 );
ary_data.push_back( foo_parse_data_1 );
ary_data.push_back( foo_parse_data_2 );
ary_data.push_back( foo_parse_data_3 );
for ( auto i = 0; i < 4; ++i ) {
ary_call[i]();
ary_data[i]();
}
return 0;
}
If it is just a static list of functions, put them into one function then call that.
Like:
void foo_network() {
void foo_network_call_1();
void foo_network_call_2();
void foo_network_call_3();
void foo_network_call_4();
}
two answer above is correct
the only way is function pointer
i usually write this model for my codes
typedef void (*NetworkFunc)(void);
typedef void (*ParseFunc)(void);
const NetworkFunc NetworkFunctions[] = {
network_func_1,
network_func_2,
...
};
const NetworkFunctions_Length = sizeof(NetworkFunctions) / sizeof(NetworkFunctions[0]);
const ParseFunc ParseFunctions[] = {
parse_func_1,
parse_func_2,
...
};
const ParseFunctions_Length = sizeof(ParseFunctions) / sizeof(ParseFunctions[0]);
now you can use it like this
for (i =0; i < NetworkFunctions_Length; i++) {
NetworkFunctions[i]();
}
for (i =0; i < ParseFunctions_Length; i++) {
ParseFunctions[i]();
}
Edit:
this is alternative c++ example
#include <iostream>
#include <functional>
using namespace std;
typedef function<void(void)> PrintFunc;
void Print_A(void);
void Print_B(void);
void Print_C(void);
const PrintFunc PrintFunctions[] = {
Print_A,
Print_B,
Print_C,
};
const int PrintFunctions_Length = sizeof(PrintFunctions) / sizeof(PrintFunctions[0]);
int main(void) {
for (int i = 0; i < PrintFunctions_Length; i++) {
PrintFunctions[i]();
}
}
void Print_A(void) {
cout << "A\n";
}
void Print_B(void) {
cout << "B\n";
}
void Print_C(void) {
cout << "C\n";
}
you can try to use an array of function pointers and every index will be a different function, that way the i indexing will work.
void (*network_call_arr[])() = {foo_network_call_1, foo_network_call_2, foo_network_call_3, foo_network_call_4};
void (*parse_data_arr[]() = {foo_parse_data_1, foo_parse_data_2, foo_parse_data_3, foo_parse_data_4};
and just call an index to a pointer from the for loop.
for (int i=0; i<4; ++i)
{
network_call_arr[i]();
parse_data_arr[i]();
}
You could also use a switch, which under optimization will probably compile to a jump table.
for (int i=1; i<5; ++i)
{ switch( i)
{ case 1:
foo_network_call_1();
foo_parse_data_1();
break;
case 2:
foo_network_call_2();
foo_parse_data_2();
break;
// etc
}
}
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
void foo_network_call_1(int data) {
cout <<"foo_network_call_1"<<endl;
}
void foo_network_call_2(int data) {
cout <<"foo_network_call_2"<<endl;
}
void foo_network_call_3(int data) {
cout <<"foo_network_call_3"<<endl;
}
void foo_network_call_4(int data) {
cout <<"foo_network_call_4"<<endl;
}
void foo_parse_data_1(string data) {
cout <<"foo_parse_data_1"<<endl;
}
void foo_parse_data_2(string data) {
cout <<"foo_parse_data_2"<<endl;
}
void foo_parse_data_3(string data) {
cout <<"foo_parse_data_3"<<endl;
}
void foo_parse_data_4(string data) {
cout <<"foo_parse_data_4"<<endl;
}
typedef std::function<void(int)> NewWorkFunc;
typedef std::function<void(string)> ParseDatFunc;
int main(int argc, char *argv[])
{
std::vector<NewWorkFunc> arrNetworkCalls;
std::vector<ParseDatFunc> arrParsedataCalls;
arrNetworkCalls.push_back(foo_network_call_1);
arrNetworkCalls.push_back(foo_network_call_2);
arrNetworkCalls.push_back(foo_network_call_3);
arrNetworkCalls.push_back(foo_network_call_4);
arrParsedataCalls.push_back(foo_parse_data_1);
arrParsedataCalls.push_back(foo_parse_data_2);
arrParsedataCalls.push_back(foo_parse_data_3);
arrParsedataCalls.push_back(foo_parse_data_4);
for(int i=0; i<4; ++i) {
arrNetworkCalls[i](i);
arrParsedataCalls[i](std::to_string(i));
}
return 0;
}

Non overwriting object

Hello I have four files: AllOnesGA.cpp, GeneticAlgorithm.h, Population.h, Individual.h
And I don't know why individual.getFitness() give me -1 and not 2 that is the last value that I give it with the method setFitness
I simplified my code
int main()
{
GeneticAlgorithm ga(100);
Population population = ga.initPopulation(50);
ga.evalPopulation(population);
ga.isTerminationConditionMet(population);
...
In geneticAlgorithm
void evalPopulation(Population population)
{
double populationFitness = 0;
for (Individual individual : population.getIndividual())
{
individual.setFitness(2);
}
}
bool isTerminationConditionMet(Population population)
{
for(Individual individual :population.getIndividual())
{
cout<<individual.getFitness()<<endl; //this gives -1 and not 2
}
}
and in Individual.h
class Individual{
public:
Individual(vector<int> chromosome2)
:chromosome(chromosome2),chromosomeLength(chromosome2.size())
{}
Individual(int chromosomeLength)
:chromosomeLength(chromosomeLength)
{
for(int gene=0;gene<chromosomeLength;gene++)
{
chromosome.push_back(gene);
}
}
int getChromosomeLength()
{
return chromosomeLength;
}
vector<int> getChromosome()
{
return chromosome;
}
int getGene(int offset)
{
return chromosome[offset];
}
void setFitness(double fitness)
{
this->fitness=fitness;
}
double getFitness()
{
return fitness;
}
private:
vector<int> chromosome;
double fitness=-1.0;
int chromosomeLength;
from Population.h
...
vector <Individual> getIndividual()
{
return this->population;
}
...
private:
vector <Individual> population;
But don't confuse the object population from AllOnesGA.cpp and the population object from Population.h that is a vector.
Any recomendation?

Too many initializers while printing char 2D array

#include<iostream>
using namespace std;
// bool turnright(char **arr,int &x,int &y,bool &quit)
// {}
// bool turnright(char **arr,int &x,int &y,bool &quit)
// {}
// bool moveforward(char **arr,int &x,int &y,bool &quit)
// {}
// bool movebackward(char **arr,int &x,int &y,bool &quit)
// {
// }
void print(char arr[][12])
{
for (int i=0;i<12;i++)
{
for (int j=0;j<12;j++)
{
cout<<arr[i][j];
}
cout<<endl;
}
}
int main()
{
char arr[12][12]={
{'#','#','#','#','#','#','#','#','#','#','#','#'},
{'#','.','.','.','#','.','.','.','.','.','.','#'},
{'#','.','#','.','#','.','#','#','#','#','.','#'},
{'#','#','#','.','#','.','.','.','.','#','.','#'},
{'#','.','.','.','.','#','#','#','.','#','.','.'},
{'#','.','.','.','.','#','#','#','.','#','.','.'},
{'#','.','.','#','.','#','.','#','.','#','.','#'},
{'#','#','.','#','.','#','.','#','.','#','.','#'},
{'#','.','.','.','.','.','.','.','.','#','.','#'},
{'#','#','#','#','#','#','.','#','#','#','.','#'},
{'.','.','.','.','.','.','.','.','#','.','.','.','#'},
{'#','#','#','#','#','#','#','#','#','#','#','#'}
};
// bool quit=false;
// int Ix;
// int IY;
// while(!quit)
// {
// moveforward();
// turnfight();
// if (!moveforward())
// {
// turnleft();
// if (!turnleft)
// {
// moveback();
// turnleft();
// if(!turnleft())
// {
// turnright();
// }
// }
// }
// }
print(arr);
}
I am trying to write code for traversing a maze while printing maze I am getting an error too many initiallizers although i have given number of rows and columns properly could any one please tell me where i am wrong ...
I reformatted your array initialization and see that row 11 has 13 elements which won't fit in an [12][12] array:
char arr[12][12]={
{'#','#','#','#','#','#','#','#','#','#','#','#'},
{'#','.','.','.','#','.','.','.','.','.','.','#'},
{'#','.','#','.','#','.','#','#','#','#','.','#'},
{'#','#','#','.','#','.','.','.','.','#','.','#'},
{'#','.','.','.','.','#','#','#','.','#','.','.'},
{'#','.','.','.','.','#','#','#','.','#','.','.'},
{'#','.','.','#','.','#','.','#','.','#','.','#'},
{'#','#','.','#','.','#','.','#','.','#','.','#'},
{'#','.','.','.','.','.','.','.','.','#','.','#'},
{'#','#','#','#','#','#','.','#','#','#','.','#'},
{'.','.','.','.','.','.','.','.','#','.','.','.','#'},
{'#','#','#','#','#','#','#','#','#','#','#','#'}
};

Error message saying Runtime Error (SEG) keeps coming up

I submitted my solution for a problem( http://opc.iarcs.org.in/index.php/problems/WORDLIST ) to the site .It is served by an online judge.Every time i submit it, it says runtime error and shows the following message :
Runtime Error: SEG
Description: Segmentation fault
Runtime: 0
What is this fault and how do i fix it?
Note:My knowledge of c++ is intermediate and i would be grateful if you could explain it in a simple way
This is my code for the problem:
#include<iostream>
#include<ctype.h>
#include<string.h>
using namespace std;
class problem
{
public:
int nol,k,j,w,cp;
char inp[1000][80],qed[1000][80];
problem()
{
k=j=w=cp=0;
}
void input()
{
cin>>nol;cin.get();
for(int i=0;i<nol;i+=1)
{
cin.getline(inp[i],80);
cin.clear();
}
cout<<endl;
lineprocess();
}
void lineprocess()
{
if(k<nol)
wordprocess();
else
display();
}
void wordprocess()
{
for(;;)
{
if(ch(inp[k][cp]))
{qed[w][j]=0;break;}
else
{
qed[w][j]=tolower(inp[k][cp]);
j+=1;cp+=1;
}
}
decide();
}
void decide()
{
if(inp[k][cp]==0)
{
w+=1;
cp=0;
j=0;
k+=1;
lineprocess();
}
else
{
w+=1;
j=0;
cp+=1;
wordprocess();
}
}
int ch(char a)
{
if(!isalpha(a))
return 1;
else return 0;
}
void display()
{
char dumm[80]="";
qed[w][0]='\0';
sortarray();
removerep();
for(int i=0;i<=w;i+=1)
if(strcmp(qed[i],dumm)!=0)
if(strcmp(qed[i],qed[i+1])!=0)
cout<<qed[i]<<endl;
}
void sortarray()
{
char ub[80];
for(;checksort();)
{
for(int q=0;q<w;q++)
{
if(strcmp(qed[q],qed[q+1])>0)
{
strcpy(ub,qed[q]);
strcpy(qed[q],qed[q+1]);
strcpy(qed[q+1],ub);
}
}
}
}
int checksort()
{
int t=0;
for(int i=0;i<w;i+=1)
{
if(strcmp(qed[i],qed[i+1])>0)
{t+=1;break;}
}
return t;
}
void removerep()
{
int nodw=0;
for(int i=0;i<w;i+=1)
if(strcmp(qed[i],qed[i+1])!=0)
nodw+=1;
cout<<nodw<<endl;
}
};
int main()
{
problem r2d2;
r2d2.input();
return 0;
}
From the linked page:
You may assume that N ≤ 10000
Since you are using
char inp[1000][80],qed[1000][80];
you are likely accessing memory beyond the valid range, which will cause you problems. Change them to:
char inp[10000][80],qed[10000][80];

Inheritance doesn't work when using loop

I have a small problem with inheritance in my code - it suddenly stops working when I add identical code in another "if" statement in my loop.
Here is the code I use for "main.cpp":
#include "bibl.h"
using namespace std;
int main()
{
int o;
Vec2 test;
while(1)
{
cout<<"1. Add item and show."<<endl<<"2. Show."<<endl;
cin>>o;
if(o==1)
{
InhItem a("Test",100);
test.addItem(&a);
cout<<"This show works:"<<endl;
test.getVec1(0)->getItem(0)->Show();//This code works.
}
else if(o==2)
{
cout<<"This show doesn't work:"<<endl;
test.getVec1(0)->getItem(0)->Show();//This doesn't.
}
}
system("pause");
return 0;
}
And the code for "bibl.h":
#ifndef TEST1
#define TEST1
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Item
{
protected:
string im;
string theme;
public:
Item(string im=" ", string theme=" "):im(im),theme(theme)
{
}
~Item()
{
}
string getTheme()
{
return theme;
}
virtual void Show()
{
}
};
class InhItem:public Item
{
int tst;
public:
InhItem(string im=" ", int tst=0):Item(im),tst(tst)
{
}
~InhItem()
{
}
void Show()
{
cout<<tst<<endl;
}
};
class Vec1
{
vector<Item*> Vec1a;
string theme;
public:
Vec1(string theme=" "):theme(theme)
{
}
~Vec1()
{
}
void addToVec1a(Item *item)
{
Vec1a.push_back(item);
}
string getTheme()
{
return theme;
}
Item *getItem(int p)
{
return Vec1a[p];
}
};
class Vec2
{
vector<Vec1*> Vec2a;
public:
Vec2()
{
}
~Vec2()
{
}
void addToVec2(Vec1 *vec1)
{
Vec2a.push_back(vec1);
}
void addItem(Item *item)
{
for(int i=0;i<=Vec2a.size();i++)
{
if(i==Vec2a.size())
{
addToVec2(new Vec1(item->getTheme()));
Vec2a[i]->addToVec1a(item);
break;
}
else if(Vec2a[i]->getTheme().compare(item->getTheme())==0)
{
Vec2a[i]->addToVec1a(item);
break;
}
}
}
Vec1 *getVec1(int r)
{
return Vec2a[r];
}
};
#endif
When I try to use the 2nd "if" after adding the item with 1st, it doesn't show - in 1st "if" test.getVec1(0)->getItem(0)->Show(); works, but in another it doesn't.
What is the cause of this problem and how can I fix it?