I have the following code:
struct elements
{
char status;
int value;
};
class matrix
{
vector<vector <elements> > mat;
int varNum;
int ConNum;
public:
void resetmatrix(int varnum, int connum)
{
varNum = varnum;
ConNum = connum;
mat.resize(connum, vector<elements>(varnum) );
}
matrix(int x, int y)
{
varNum = 0;
ConNum = 0;
}
};
matrix mat(0,0);
int main(int argc, char *argv[]) //main function
{
int variables,cubes;
variables=25;
cubes= 10000000;
cout<<"Variables= "<<variables<<endl<<"Cubes= "<<cubes<<endl;
mat.resetmatrix(variables, cubes);
cout<<"hello";
return 0;
}
I get the following error
I thought this type of error only occurs when you haven't resized your vector. But I am resizing it. Can anyone tell me why this happens? is it because the value of cubes is very high (10 million)?
I was writing an adjacent list-based graph with weighted edges. My goal is to implement a graph to test the Djikstra's shortest path algorithm. I came to a bummer when I was implementing the removeEdge function. I looked at the build messages but I didn't have a clue as in what the errors below are about.
There are a few warnings before this one below but they are minor as it compiled and ran ok.
c:\program files (x86)\codeblocks\mingw\bin..\lib\gcc\mingw32\4.7.1\include\c++\bits\list.tcc||In instantiation of 'void std::list<_Tp, _Alloc>::remove(const value_type&) [with _Tp = Edge; _Alloc = std::allocator; std::list<_Tp, _Alloc>::value_type = Edge]':|
This is the error generated.
c:\program files (x86)\codeblocks\mingw\bin..\lib\gcc\mingw32\4.7.1\include\c++\bits\list.tcc|249|error: no match for 'operator==' in '__first.std::_List_iterator<_Tp>::operator*() == __value'|
Now, the code:
#ifndef WEIGHTED_ADJACENT_LIST_GRAPH_H
#define WEIGHTED_ADJACENT_LIST_GRAPH_H
#include <list>
#include <forward_list>
#include <stack>
#include <string>
using namespace std;
typedef int Weight;
class Edge;
class Vertex {
friend class Edge;
int num;
string name;
public:
Vertex();
Vertex(int n, string v_name){
num = n;
name = v_name;
}
int getNum() const{
return num;
}
string getName() const{
return name;
}
void setNum(int new_num){
num = new_num;
}
void setName(string new_name){
name = new_name;
}
};
class Edge {
Weight weight;
Vertex src;
Vertex dest;
public:
Edge();
Edge(Vertex s, Vertex d, Weight w):src(s), dest(d),weight(w){}
/*
Edge(Vertex s, Vertex d, Weight w){
src = s;
dest = d;
weight = w;
}
*/
Weight getWeight() const{
return weight;
}
int getSrcNum() const{
return src.num;
}
int getDestNum() const{
return dest.num;
}
};
class AdjacentList{
int num_Vertices;
list<Edge> *adj;
public:
AdjacentList();
AdjacentList(int n){
num_Vertices = n;
}
void addEdge(Vertex &i, Edge &j){
adj[i.getNum()].push_back(j);
}
void removeEdge(Vertex &i, Edge j){
if(!adj[i.getNum()].empty())
{
adj[i.getNum()].remove(j);
}
else{
cerr<<"Adjacent list underflow in removeEdge function"<<endl;
}
}
};
#endif
Please be noted that this graph is incomplete. A lot functions still need to be implemented there. Does anyone know what's wrong with this data structure code?
You haven't provided an operator== for Edge, I have no idea exactly how you want to specify which Edges are equal but you'll need something like the following defined before you use remove
bool operator==(Edge const& lhs, Edge const& rhs)
{
return
lhs.getWeight() == rhs.getWeight() &&
lhs.getSrcNum() == rhs.getSrcNum() &&
lhs.getDestNum() == rhs.getDestNum();
}
The following code:
std::vector< int > keysDown;
for each ( int currentKey in keysDown )
{
}
is throwing an intellisense error:
1 IntelliSense: a 'for each' statement cannot operate on an expression of type "std::vector<int, std::allocator<int>>"
but it seems to compile and run, any ideas?
does not seem to iterate through the vector:
void Keyboard::AddKeyToVector( int key )
{
keysDown.push_back( key );
}
void Keyboard::RemoveKeyFromVector( int key )
{
std::vector< int > keysDown; // Placing this here for brevity, it's declared in the class's .h and is instanciated globally
int i;
for( int currentKey : keysDown )
{
if( currentKey == key )
{
keysDown.erase(keysDown.begin()+i);
}
i++;
}
}
What is the error in this file?
I get:
foo2.cpp:9: error: expected primary-expression before '(' token
foo2.cpp:9: error: expected primary-expression before 'int'
foo2.cpp:9: error: expected ';' before '{' token
int main(void)
{
class X {
int i;
public:
X(int ii = 0);
};
X::X(int ii) { i = ii; }
return 0;
}
First, may I ask, WHY?
Second, you can't provide an implementation inside a method (including main). If you must do this, keep the implementation inline:
int main()
{
class X {
int i;
public:
X(int ii = 0){ i = ii; }
};
return 0;
}
You cannot nest functions in C++. To modify your program, you have two alternatives. You may move your class definition outside of main, or you may put your method definition inside the class:
First alternative:
class X {
int i;
public:
X(int ii = 0);
};
X::X(int ii) { i = ii; }
int main(void)
{
return 0;
}
Second alternative:
int main(void)
{
class X {
int i;
public:
X(int ii = 0) { i = ii; }
};
return 0;
}
I've got weird problem. I'm trying to write simple game in C++, but I failed on objects and data types. There's a code:
// C++
// Statki
#include <stdio.h>
#include <time.h>
#include <map>
#include <vector>
#include <string>
#include <list>
#define D true
using namespace std;
void _(char* message){printf("%s\n",message);};
struct relpoint { int x,y; };
struct point { int x,y; };
struct size { int w,h; };
map<const char*, vector<relpoint> > shipshape;
list<char*> shipTypes = {"XS", "S", "M", "L", "XL"};
string alpha="ABCDEFGHIJKLMNOPRSTUVWXYZ";
enum fieldtype { UNKNOWN=-1,EMPTY=0,SHIP=1,HIT=2,MISS=3,};
enum rotation { EAST=0, SOUTH=1, WEST=2, NORTH=3 };
class Ship
{
char* type;
};
class Sea
{
public:
void init(size mapsize) { init( mapsize, EMPTY ); };
void init(size mapsize, fieldtype fill)
{
if(D)printf("Generating sea\n");
vector<fieldtype> v;
seamap.reserve(mapsize.h);
v.reserve(mapsize.w);
for (int y=0; y<mapsize.h; y++)
{
v.clear();
for(int x=0; x<mapsize.w; x++)
{
v.push_back(fill);
}
seamap.push_back(v);
}
view();
};
bool place_ship(Ship ship);
void view()
{
for( vector< vector<fieldtype> >::const_iterator yy = seamap.begin(); yy != seamap.end(); ++yy )
{
for( vector<fieldtype>::const_iterator xx = (*yy).begin(); xx != (*yy).end(); ++xx )
{
if(D)printf("%d ", *xx);
}
if(D)printf("\n");
}
};
private:
vector< vector<fieldtype> > seamap;
};
class Game
{
public:
void initmap(size mapsize)
{
if(D) printf("\nInit %d×%d map\n", mapsize.w, mapsize.h);
(*enemymap).init(mapsize, UNKNOWN);
//(*selfmap).init(mapsize);
};
bool placeship(string type, point position, rotation rotate);
fieldtype shoot(point target);
void viewmap(){(*selfmap).view();};
bool eog();
Sea * enemymap;
Sea * selfmap;
};
class Bot
{
public:
void init(size mapsize)
{
if(D)_("Init Bot");
}
private:
Game * g;
};
class Player
{
public:
Player() { if(D){_("Player fake init");} };
void init(size mapsize)
{
(*g).initmap(mapsize);
};
void viewmap(){(*g).viewmap();};
private:
Game * g;
};
class Router
{
public:
void startgame();
void welcomescreen()
{
printf("\n\n\n\t\t\tShips minigame\n\t\t\t\tby Kris\n\n");
mainmenu();
};
void mainmenu()
{
printf("Menu (type letter):\n\tN: New game\n\tS: Settings\n\tQ: Quit game\n\n > ");
char opt;
opt = toupper(getchar());
size ms;
switch(opt)
{
case 'N':
ms = getmapsize();
(*P1).init(ms);
(*P2).init(ms);
break;
case 'S':
break;
case 'Q':
break;
default:
printf("Invalid option %c", opt);
mainmenu();
}
};
private:
Player * P1;
Bot * P2;
size getmapsize()
{
size ms;
printf("\nSet map size (X Y)\n > ");
scanf("%d %d", &ms.w, &ms.h);
return ms;
};
};
int main () {
vector<relpoint> shp;
shp.reserve(5);
list<char*>::const_iterator tp = shipTypes.begin();
shp.push_back({0,0});
shipshape[*(tp++)] = shp;
shp.push_back({1,0});
shipshape[*(tp++)] = shp;
shp.push_back({2,0});
shipshape[*(tp++)] = shp;
shp.push_back({3,0});
shipshape[*(tp++)] = shp;
shp.push_back({2,1});
shipshape[*tp] = shp;
Router R;
R.welcomescreen();
printf("\n\n");
return 0;
}
It can be compiled, but after line Init 5×5 map program stops with Naruszenie ochrony pamięci (Memory access violation in polish) error. Problem seems to occur at both Sea::init() functions.
I'm compiling it with g++ -std=c++0x -Wno-write-strings ships2.cpp (to prevent warnings) on Ubuntu.
Any idea what's wrong with it?
All the classes contain pointers, but you never seem to initialize the pointers or allocate space for the objects they should point to.
Doing this
(*enemymap).init(mapsize, UNKNOWN);
when enemymap doesn't point anywhere, is an almost sure way to get an access violation.
You are using an uninitialized pointer. You can fix it by instantiating an object here, or in a constructor somewhere else.
Here is an example of instantiating in the initmap call.
void initmap(size mapsize)
{
// Initialize the pointer by instantiating a class
enemymap = new Sea;
if(D) printf("\nInit %d×%d map\n", mapsize.w, mapsize.h);
(*enemymap).init(mapsize, UNKNOWN);
//(*selfmap).init(mapsize);
};
+1 for Bo. But for your own sake:
compile with -g and then then
gdb ./mygame.bin
type 'run'
after setting the map size 5 5 :
Program received signal SIGSEGV, Segmentation fault.
mainmenu (this=<optimized out>) at memacvio.cpp:158
158 (*P1).init(ms);
This should tell you that P1 is probably not a valid poiner.