Search Results

Search found 1031 results on 42 pages for 'iostream'.

Page 8/42 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Error with Phoenix placeholder _val in Boost.Spirit.Lex :(

    - by GooRoo
    Hello, everybody. I'm newbie in Boost.Spirit.Lex. Some strange error appears every time I try to use lex::_val in semantics actions in my simple lexer: #ifndef _TOKENS_H_ #define _TOKENS_H_ #include <iostream> #include <string> #include <boost/spirit/include/lex_lexertl.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_statement.hpp> #include <boost/spirit/include/phoenix_container.hpp> namespace lex = boost::spirit::lex; namespace phx = boost::phoenix; enum tokenids { ID_IDENTIFICATOR = 1, ID_CONSTANT, ID_OPERATION, ID_BRACKET, ID_WHITESPACES }; template <typename Lexer> struct mega_tokens : lex::lexer<Lexer> { mega_tokens() : identifier(L"[a-zA-Z_][a-zA-Z0-9_]*", ID_IDENTIFICATOR) , constant (L"[0-9]+(\\.[0-9]+)?", ID_CONSTANT ) , operation (L"[\\+\\-\\*/]", ID_OPERATION ) , bracket (L"[\\(\\)\\[\\]]", ID_BRACKET ) { using lex::_tokenid; using lex::_val; using phx::val; this->self = operation [ std::wcout << val(L'<') << _tokenid // << val(L':') << lex::_val << val(L'>') ] | identifier [ std::wcout << val(L'<') << _tokenid << val(L':') << _val << val(L'>') ] | constant [ std::wcout << val(L'<') << _tokenid // << val(L':') << _val << val(L'>') ] | bracket [ std::wcout << phx::val(lex::_val) << val(L'<') << _tokenid // << val(L':') << lex::_val << val(L'>') ] ; } lex::token_def<wchar_t, wchar_t> operation; lex::token_def<std::wstring, wchar_t> identifier; lex::token_def<double, wchar_t> constant; lex::token_def<wchar_t, wchar_t> bracket; }; #endif // _TOKENS_H_ and #include <cstdlib> #include <iostream> #include <locale> #include <boost/spirit/include/lex_lexertl.hpp> #include "tokens.h" int main() { setlocale(LC_ALL, "Russian"); namespace lex = boost::spirit::lex; typedef std::wstring::iterator base_iterator; typedef lex::lexertl::token < base_iterator, boost::mpl::vector<wchar_t, std::wstring, double, wchar_t>, boost::mpl::true_ > token_type; typedef lex::lexertl::actor_lexer<token_type> lexer_type; typedef mega_tokens<lexer_type>::iterator_type iterator_type; mega_tokens<lexer_type> mega_lexer; std::wstring str = L"alfa+x1*(2.836-x2[i])"; base_iterator first = str.begin(); bool r = lex::tokenize(first, str.end(), mega_lexer); if (r) { std::wcout << L"Success" << std::endl; } else { std::wstring rest(first, str.end()); std::wcerr << L"Lexical analysis failed\n" << L"stopped at: \"" << rest << L"\"\n"; } return EXIT_SUCCESS; } This code causes an error in Boost header 'boost/spirit/home/lex/argument.hpp' on line 167 while compiling: return: can't convert 'const boost::variant' to 'boost::variant &' When I don't use lex::_val program compiles with no errors. Obviously, I use _val in wrong way, but I do not know how to do this correctly. Help, please! :) P.S. And sorry for my terrible English…

    Read the article

  • LIbrary issue: How do I set up QtWebKit to parse HTML?

    - by user560106
    Nick Presta showed that you can parse HTML with qt here: Library Recommendation: C++ HTML Parser However, when I attempt to build this, I get an access violation on the "QWebFrame* frame = page.mainFrame();" line. What am I doing wrong? #include <QtWebKit\QWebElement> #include <QtWebKit\QWebView> #include <QtWebKit\QWebFrame> #include <QtWebKit\QWebPage> #include <iostream> int main() { QWebPage page; QWebFrame* frame = page.mainFrame(); frame->setHtml( "<html><head></head><body></body></html>" ); QWebElement document = frame->documentElement(); return 0; }

    Read the article

  • What does the C compiler error "looks like a function definition, but there is no parameter list;" m

    - by user312309
    #include <iostream> #include <fstream> using namespace std; int main { int num1, num2; ifstream infile; ostream outfile; infile.open("input.dat"); outfile.open("output.dat"); infile >> num 1 >> num 2; outfile << "Sum = " << num1 + num2 << endl; infile.close() outfile.close() return 0; } this is what i did and when i compile it, i got this error that said error C2470: 'main' : looks like a function definition, but there is no parameter list; skipping apperent body please dont hate me :( i am new at this computer science....

    Read the article

  • What does msvc 6 throw when an integer divide by zero occurs?

    - by EvilTeach
    I have been doing a bit of experimenting, and have discovered that an exception is being thrown, when an integer divide by zero occurs. #include <iostream> #include <stdexcept> using namespace std; int main ( void ) { try { int x = 3; int y = 0; int z = x / y; cout << "Didn't throw or signal" << endl; } catch (std::exception &e) { cout << "Caught exception " << e.what() << endl; } return 0; } Clearly it is not throwing a std::exception. What else might it be throwing?

    Read the article

  • daynamic 2d array in c++ and memory leaks

    - by SepiDev
    Hi guys, i wrote this code, it runs ok, but when i check it under Valgrind it catches 2 problems, since i can not interpret valgrind's messages i will appreciate if anyone explain me more and tell me where is the problem!!! here is the code: #include <iostream> #define width 70000 #define height 10000 using namespace std; int main(void) { int** pint; pint = new int*[height]; for(int i = 0; i < height; i++) pint[i] = new int[width]; for(int i = 0; i < height; i++){ delete[] pint[i]; pint[i] = NULL; } delete[] pint; pint = NULL; return 1; }

    Read the article

  • Where is the virtual function call overhead?

    - by Semen Semenych
    Hello everybody, I'm trying to benchmark the difference between a function pointer call and a virtual function call. To do this, I have written two pieces of code, that do the same mathematical computation over an array. One variant uses an array of pointers to functions and calls those in a loop. The other variant uses an array of pointers to a base class and calls its virtual function, which is overloaded in the derived classes to do absolutely the same thing as the functions in the first variant. Then I print the time elapsed and use a simple shell script to run the benchmark many times and compute the average run time. Here is the code: #include <iostream> #include <cstdlib> #include <ctime> #include <cmath> using namespace std; long long timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p) { return ((timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) - ((timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec); } void function_not( double *d ) { *d = sin(*d); } void function_and( double *d ) { *d = cos(*d); } void function_or( double *d ) { *d = tan(*d); } void function_xor( double *d ) { *d = sqrt(*d); } void ( * const function_table[4] )( double* ) = { &function_not, &function_and, &function_or, &function_xor }; int main(void) { srand(time(0)); void ( * index_array[100000] )( double * ); double array[100000]; for ( long int i = 0; i < 100000; ++i ) { index_array[i] = function_table[ rand() % 4 ]; array[i] = ( double )( rand() / 1000 ); } struct timespec start, end; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); for ( long int i = 0; i < 100000; ++i ) { index_array[i]( &array[i] ); } clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); unsigned long long time_elapsed = timespecDiff(&end, &start); cout << time_elapsed / 1000000000.0 << endl; } and here is the virtual function variant: #include <iostream> #include <cstdlib> #include <ctime> #include <cmath> using namespace std; long long timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p) { return ((timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) - ((timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec); } class A { public: virtual void calculate( double *i ) = 0; }; class A1 : public A { public: void calculate( double *i ) { *i = sin(*i); } }; class A2 : public A { public: void calculate( double *i ) { *i = cos(*i); } }; class A3 : public A { public: void calculate( double *i ) { *i = tan(*i); } }; class A4 : public A { public: void calculate( double *i ) { *i = sqrt(*i); } }; int main(void) { srand(time(0)); A *base[100000]; double array[100000]; for ( long int i = 0; i < 100000; ++i ) { array[i] = ( double )( rand() / 1000 ); switch ( rand() % 4 ) { case 0: base[i] = new A1(); break; case 1: base[i] = new A2(); break; case 2: base[i] = new A3(); break; case 3: base[i] = new A4(); break; } } struct timespec start, end; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); for ( int i = 0; i < 100000; ++i ) { base[i]->calculate( &array[i] ); } clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); unsigned long long time_elapsed = timespecDiff(&end, &start); cout << time_elapsed / 1000000000.0 << endl; } My system is LInux, Fedora 13, gcc 4.4.2. The code is compiled it with g++ -O3. The first one is test1, the second is test2. Now I see this in console: [Ignat@localhost circuit_testing]$ ./test2 && ./test2 0.0153142 0.0153166 Well, more or less, I think. And then, this: [Ignat@localhost circuit_testing]$ ./test2 && ./test2 0.01531 0.0152476 Where are the 25% which should be visible? How can the first executable be even slower than the second one? I'm asking this because I'm doing a project which involves calling a lot of small functions in a row like this in order to compute the values of an array, and the code I've inherited does a very complex manipulation to avoid the virtual function call overhead. Now where is this famous call overhead?

    Read the article

  • string parsing to double fails in C++

    - by helixed
    Here's a fun one I've been trying to figure out. I have the following program: #include <iostream> #include <string> #include <sstream> using namespace std; int main(int argc, char *argv[]) { string s("5"); istringstream stream(s); double theValue; stream >> theValue; cout << theValue << endl; cout << stream.fail(); } The output is: 0 1 I don't understand why this is failing. Could somebody please tell me what I'm doing wrong? Thanks, helixed

    Read the article

  • Why is there ambiguity in this diamond pattern?

    - by cambr
    #include <iostream> using namespace std; class A { public: void eat(){ cout<<"A";} }; class B: public A { public: void eat(){ cout<<"B";} }; class C: public A { public: void eat(){ cout<<"C";} }; class D: public B,C { public: void eat(){ cout<<"D";} }; int main(){ A *a = new D(); a->eat(); } I am not sure this is called diamond problem or not, but why doesn't this work? When I said, a->eat() (remember eat() is not virtual), there is only one possible eat() to call, that of A. Why then, do I get this error: 'A' is an ambiguous base of 'D'

    Read the article

  • pointer reference type

    - by Codenotguru
    I am trying to write a function that takes a pointer argument, modifies what the pointer points to, and then returns the destination of the pointer as a reference. I am gettin the following error: cannot convert int***' toint*' in return| Code: #include <iostream> using namespace std; int* increment(int** i) { i++; return &i;} int main() { int a=24; int *p=&a; int *p2; p2=increment(&p); cout<<p2; } Thanks for helping!

    Read the article

  • msginit email address command line argument?

    - by C.W.Holeman II
    msginit prompts for an email address. Is there a way to tell msginit what email address to use without being prompted for it such as a command line argument? cat >hellogt.cxx <<EOF // hellogt.cxx #include <libintl.h> #include <locale.h> #include <iostream> int main (){ setlocale(LC_ALL, ""); bindtextdomain("hellogt", "./"); textdomain( "hellogt" ); std::cout << gettext("hello, world!") << std::endl; } EOF g++ -ohellogt hellogt.cxx xgettext -d hellogt -o hellogt.pot hellogt.cxx msginit -l es_MX -o spanish.po -i hellogt.pot

    Read the article

  • Static Member Variables of the Same Class in C++

    - by helixed
    I'm trying to create a class which contains a static pointer to an instance of itself. Here's an example: A.h: #include <iostream> #ifndef _A_H #define _A_H class A { static A * a; }; A * a = NULL; #endif However, when I include A.h in another file, such as: #include "A.h" class B { }; I get the following error: ld: duplicate symbol _a in /Users/helixed/Desktop/Example/build/Example.build/Debug/Example.build/Objects-normal/x86_64/B.o and /Users/helixed/Desktop/Example/build/Example.build/Debug/Examplebuild/Objects-normal/x86_64/A.o I'm using the Xcode default compiler on Mac OS X Snow Leopard. Thanks, helixed

    Read the article

  • error with io stream

    - by Alexander
    What is the problem with the last two statements in the code? #include <iostream> using namespace std; int main() { cout << "2 + 4 = " << 2 + 4 << endl; cout << "2 * 4 = " << 2 * 4 << endl; cout << "2 | 4 = " << 2 | 4 << endl; cout << "2 & 4 = " << 2 & 4 << endl; What should I do to fix this?

    Read the article

  • what's wrong in my C program ?

    - by user292084
    a cpp file: #include <iostream> #include <jni.h> #include "Hello.h" #include "windows.h" #include "stdafx.h" #define HINSTANCE "hDll" typedef void(__stdcall *Print_)(); int main(){ HINSTANCE hDll; //DLL?? Print_ print_; //???? hDll = LoadLibrary("Hello.dll"); if (hDll != NULL) { print_ = (Print_)GetProcAddress(hDll,"Java_Hello_sayHello@8"); if(print_!=NULL) { print_(); } FreeLibrary(hDll); } return 0; } //there is something wrong, it prints: http://i983.photobucket.com/albums/ae311/keatingWang/c_wrong.png ??????? means : Undeclared identifier

    Read the article

  • sem_open() error: "undefined reference to sem_open()" on linux (Ubuntu 10.10)

    - by Robin
    So I am getting the error: "undefined reference to sem_open()" even though I have include the semaphore.h header. The same thing is happening for all my pthread function calls (mutex, pthread_create, etc). Any thoughts? I am using the following command to compile: g++ '/home/robin/Desktop/main.cpp' -o '/home/robin/Desktop/main.out' #include <iostream> using namespace std; #include <pthread.h> #include <semaphore.h> #include <fcntl.h> const char *serverControl = "/serverControl"; sem_t* semID; int main ( int argc, char *argv[] ) { //create semaphore used to control servers semID = sem_open(serverControl,O_CREAT,O_RDWR,0); return 0; }

    Read the article

  • C++ - Conway's Game of Life & Stepping Backwards

    - by Gabe
    I was able to create a version Conway's Game of Life that either stepped forward each click, or just ran forward using a timer. (I'm doing this using Qt.) Now, I need to be able to save all previous game grids, so that I can step backwards by clicking a button. I'm trying to use a stack, and it seems like I'm pushing the old gridcells onto the stack correctly. But when I run it in QT, the grids don't change when I click BACK. I've tried different things for the last three hours, to no avail. Any ideas? gridwindow.cpp - My problem should be in here somewhere. Probably the handleBack() func. #include <iostream> #include "gridwindow.h" using namespace std; // Constructor for window. It constructs the three portions of the GUI and lays them out vertically. GridWindow::GridWindow(QWidget *parent,int rows,int cols) : QWidget(parent) { QHBoxLayout *header = setupHeader(); // Setup the title at the top. QGridLayout *grid = setupGrid(rows,cols); // Setup the grid of colored cells in the middle. QHBoxLayout *buttonRow = setupButtonRow(); // Setup the row of buttons across the bottom. QVBoxLayout *layout = new QVBoxLayout(); // Puts everything together. layout->addLayout(header); layout->addLayout(grid); layout->addLayout(buttonRow); setLayout(layout); } // Destructor. GridWindow::~GridWindow() { delete title; } // Builds header section of the GUI. QHBoxLayout* GridWindow::setupHeader() { QHBoxLayout *header = new QHBoxLayout(); // Creates horizontal box. header->setAlignment(Qt::AlignHCenter); this->title = new QLabel("CONWAY'S GAME OF LIFE",this); // Creates big, bold, centered label (title): "Conway's Game of Life." this->title->setAlignment(Qt::AlignHCenter); this->title->setFont(QFont("Arial", 32, QFont::Bold)); header->addWidget(this->title); // Adds widget to layout. return header; // Returns header to grid window. } // Builds the grid of cells. This method populates the grid's 2D array of GridCells with MxN cells. QGridLayout* GridWindow::setupGrid(int rows,int cols) { isRunning = false; QGridLayout *grid = new QGridLayout(); // Creates grid layout. grid->setHorizontalSpacing(0); // No empty spaces. Cells should be contiguous. grid->setVerticalSpacing(0); grid->setSpacing(0); grid->setAlignment(Qt::AlignHCenter); for(int i=0; i < rows; i++) //Each row is a vector of grid cells. { std::vector<GridCell*> row; // Creates new vector for current row. cells.push_back(row); for(int j=0; j < cols; j++) { GridCell *cell = new GridCell(); // Creates and adds new cell to row. cells.at(i).push_back(cell); grid->addWidget(cell,i,j); // Adds to cell to grid layout. Column expands vertically. grid->setColumnStretch(j,1); } grid->setRowStretch(i,1); // Sets row expansion horizontally. } return grid; // Returns grid. } // Builds footer section of the GUI. QHBoxLayout* GridWindow::setupButtonRow() { QHBoxLayout *buttonRow = new QHBoxLayout(); // Creates horizontal box for buttons. buttonRow->setAlignment(Qt::AlignHCenter); // Clear Button - Clears cell; sets them all to DEAD/white. QPushButton *clearButton = new QPushButton("CLEAR"); clearButton->setFixedSize(100,25); connect(clearButton, SIGNAL(clicked()), this, SLOT(handlePause())); // Pauses timer before clearing. connect(clearButton, SIGNAL(clicked()), this, SLOT(handleClear())); // Connects to clear function to make all cells DEAD/white. buttonRow->addWidget(clearButton); // Forward Button - Steps one step forward. QPushButton *forwardButton = new QPushButton("FORWARD"); forwardButton->setFixedSize(100,25); connect(forwardButton, SIGNAL(clicked()), this, SLOT(handleForward())); // Signals to handleForward function.. buttonRow->addWidget(forwardButton); // Back Button - Steps one step backward. QPushButton *backButton = new QPushButton("BACK"); backButton->setFixedSize(100,25); connect(backButton, SIGNAL(clicked()), this, SLOT(handleBack())); // Signals to handleBack funciton. buttonRow->addWidget(backButton); // Start Button - Starts game when user clicks. Or, resumes game after being paused. QPushButton *startButton = new QPushButton("START/RESUME"); startButton->setFixedSize(100,25); connect(startButton, SIGNAL(clicked()), this, SLOT(handlePause())); // Deletes current timer if there is one. Then restarts everything. connect(startButton, SIGNAL(clicked()), this, SLOT(handleStart())); // Signals to handleStart function. buttonRow->addWidget(startButton); // Pause Button - Pauses simulation of game. QPushButton *pauseButton = new QPushButton("PAUSE"); pauseButton->setFixedSize(100,25); connect(pauseButton, SIGNAL(clicked()), this, SLOT(handlePause())); // Signals to pause function which pauses timer. buttonRow->addWidget(pauseButton); // Quit Button - Exits program. QPushButton *quitButton = new QPushButton("EXIT"); quitButton->setFixedSize(100,25); connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit())); // Signals the quit slot which ends the program. buttonRow->addWidget(quitButton); return buttonRow; // Returns bottom of layout. } /* SLOT method for handling clicks on the "clear" button. Receives "clicked" signals on the "Clear" button and sets all cells to DEAD. */ void GridWindow::handleClear() { for(unsigned int row=0; row < cells.size(); row++) // Loops through current rows' cells. { for(unsigned int col=0; col < cells[row].size(); col++) // Loops through the rows'columns' cells. { GridCell *cell = cells[row][col]; // Grab the current cell & set its value to dead. cell->setType(DEAD); } } } /* SLOT method for handling clicks on the "start" button. Receives "clicked" signals on the "start" button and begins game simulation. */ void GridWindow::handleStart() { isRunning = true; // It is running. Sets isRunning to true. this->timer = new QTimer(this); // Creates new timer. connect(this->timer, SIGNAL(timeout()), this, SLOT(timerFired())); // Connect "timerFired" method class to the "timeout" signal fired by the timer. this->timer->start(500); // Timer to fire every 500 milliseconds. } /* SLOT method for handling clicks on the "pause" button. Receives "clicked" signals on the "pause" button and stops the game simulation. */ void GridWindow::handlePause() { if(isRunning) // If it is running... this->timer->stop(); // Stops the timer. isRunning = false; // Set to false. } void GridWindow::handleForward() { if(isRunning); // If it's running, do nothing. else timerFired(); // It not running, step forward one step. } void GridWindow::handleBack() { std::vector<std::vector<GridCell*> > cells2; if(isRunning); // If it's running, do nothing. else if(backStack.empty()) cout << "EMPTYYY" << endl; else { cells2 = backStack.peek(); for (unsigned int f = 0; f < cells.size(); f++) // Loop through cells' rows. { for (unsigned int g = 0; g < cells.at(f).size(); g++) // Loop through cells columns. { cells[f][g]->setType(cells2[f][g]->getType()); // Set cells[f][g]'s type to cells2[f][g]'s type. } } cout << "PRE=POP" << endl; backStack.pop(); cout << "OYYYY" << endl; } } // Accessor method - Gets the 2D vector of grid cells. std::vector<std::vector<GridCell*> >& GridWindow::getCells() { return this->cells; } /* TimerFired function: 1) 2D-Vector cells2 is declared. 2) cells2 is initliazed with loops/push_backs so that all its cells are DEAD. 3) We loop through cells, and count the number of LIVE neighbors next to a given cell. --> Depending on how many cells are living, we choose if the cell should be LIVE or DEAD in the next simulation, according to the rules. -----> We save the cell type in cell2 at the same indice (the same row and column cell in cells2). 4) After check all the cells (and save the next round values in cells 2), we set cells's gridcells equal to cells2 gridcells. --> This causes the cells to be redrawn with cells2 types (white or black). */ void GridWindow::timerFired() { backStack.push(cells); std::vector<std::vector<GridCell*> > cells2; // Holds new values for 2D vector. These are the next simulation round of cell types. for(unsigned int i = 0; i < cells.size(); i++) // Loop through the rows of cells2. (Same size as cells' rows.) { vector<GridCell*> row; // Creates Gridcell* vector to push_back into cells2. cells2.push_back(row); // Pushes back row vectors into cells2. for(unsigned int j = 0; j < cells[i].size(); j++) // Loop through the columns (the cells in each row). { GridCell *cell = new GridCell(); // Creates new GridCell. cell->setType(DEAD); // Sets cell type to DEAD/white. cells2.at(i).push_back(cell); // Pushes back the DEAD cell into cells2. } // This makes a gridwindow the same size as cells with all DEAD cells. } for (unsigned int m = 0; m < cells.size(); m++) // Loop through cells' rows. { for (unsigned int n = 0; n < cells.at(m).size(); n++) // Loop through cells' columns. { unsigned int neighbors = 0; // Counter for number of LIVE neighbors for a given cell. // We know check all different variations of cells[i][j] to count the number of living neighbors for each cell. // We check m > 0 and/or n > 0 to make sure we don't access negative indexes (ex: cells[-1][0].) // We check m < size to make sure we don't try to access rows out of the vector (ex: row 5, if only 4 rows). // We check n < row size to make sure we don't access column item out of the vector (ex: 10th item in a column of only 9 items). // If we find that the Type = 1 (it is LIVE), then we add 1 to the neighbor. // Else - we add nothing to the neighbor counter. // Neighbor is the number of LIVE cells next to the current cell. if(m > 0 && n > 0) { if (cells[m-1][n-1]->getType() == 1) neighbors += 1; } if(m > 0) { if (cells[m-1][n]->getType() == 1) neighbors += 1; if(n < (cells.at(m).size() - 1)) { if (cells[m-1][n+1]->getType() == 1) neighbors += 1; } } if(n > 0) { if (cells[m][n-1]->getType() == 1) neighbors += 1; if(m < (cells.size() - 1)) { if (cells[m+1][n-1]->getType() == 1) neighbors += 1; } } if(n < (cells.at(m).size() - 1)) { if (cells[m][n+1]->getType() == 1) neighbors += 1; } if(m < (cells.size() - 1)) { if (cells[m+1][n]->getType() == 1) neighbors += 1; } if(m < (cells.size() - 1) && n < (cells.at(m).size() - 1)) { if (cells[m+1][n+1]->getType() == 1) neighbors += 1; } // Done checking number of neighbors for cells[m][n] // Now we change cells2 if it should switch in the next simulation step. // cells2 holds the values of what cells should be on the next iteration of the game. // We can't change cells right now, or it would through off our other cell values. // Apply game rules to cells: Create new, updated grid with the roundtwo vector. // Note - LIVE is 1; DEAD is 0. if (cells[m][n]->getType() == 1 && neighbors < 2) // If cell is LIVE and has less than 2 LIVE neighbors -> Set to DEAD. cells2[m][n]->setType(DEAD); else if (cells[m][n]->getType() == 1 && neighbors > 3) // If cell is LIVE and has more than 3 LIVE neighbors -> Set to DEAD. cells2[m][n]->setType(DEAD); else if (cells[m][n]->getType() == 1 && (neighbors == 2 || neighbors == 3)) // If cell is LIVE and has 2 or 3 LIVE neighbors -> Set to LIVE. cells2[m][n]->setType(LIVE); else if (cells[m][n]->getType() == 0 && neighbors == 3) // If cell is DEAD and has 3 LIVE neighbors -> Set to LIVE. cells2[m][n]->setType(LIVE); } } // Now we've gone through all of cells, and saved the new values in cells2. // Now we loop through cells and set all the cells' types to those of cells2. for (unsigned int f = 0; f < cells.size(); f++) // Loop through cells' rows. { for (unsigned int g = 0; g < cells.at(f).size(); g++) // Loop through cells columns. { cells[f][g]->setType(cells2[f][g]->getType()); // Set cells[f][g]'s type to cells2[f][g]'s type. } } } stack.h - Here's my stack. #ifndef STACK_H_ #define STACK_H_ #include <iostream> #include "node.h" template <typename T> class Stack { private: Node<T>* top; int listSize; public: Stack(); int size() const; bool empty() const; void push(const T& value); void pop(); T& peek() const; }; template <typename T> Stack<T>::Stack() : top(NULL) { listSize = 0; } template <typename T> int Stack<T>::size() const { return listSize; } template <typename T> bool Stack<T>::empty() const { if(listSize == 0) return true; else return false; } template <typename T> void Stack<T>::push(const T& value) { Node<T>* newOne = new Node<T>(value); newOne->next = top; top = newOne; listSize++; } template <typename T> void Stack<T>::pop() { Node<T>* oldT = top; top = top->next; delete oldT; listSize--; } template <typename T> T& Stack<T>::peek() const { return top->data; // Returns data in top item. } #endif gridcell.cpp - Gridcell implementation #include <iostream> #include "gridcell.h" using namespace std; // Constructor: Creates a grid cell. GridCell::GridCell(QWidget *parent) : QFrame(parent) { this->type = DEAD; // Default: Cell is DEAD (white). setFrameStyle(QFrame::Box); // Set the frame style. This is what gives each box its black border. this->button = new QPushButton(this); //Creates button that fills entirety of each grid cell. this->button->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); // Expands button to fill space. this->button->setMinimumSize(19,19); //width,height // Min height and width of button. QHBoxLayout *layout = new QHBoxLayout(); //Creates a simple layout to hold our button and add the button to it. layout->addWidget(this->button); setLayout(layout); layout->setStretchFactor(this->button,1); // Lets the buttons expand all the way to the edges of the current frame with no space leftover layout->setContentsMargins(0,0,0,0); layout->setSpacing(0); connect(this->button,SIGNAL(clicked()),this,SLOT(handleClick())); // Connects clicked signal with handleClick slot. redrawCell(); // Calls function to redraw (set new type for) the cell. } // Basic destructor. GridCell::~GridCell() { delete this->button; } // Accessor for the cell type. CellType GridCell::getType() const { return(this->type); } // Mutator for the cell type. Also has the side effect of causing the cell to be redrawn on the GUI. void GridCell::setType(CellType type) { this->type = type; redrawCell(); // Sets type and redraws cell. } // Handler slot for button clicks. This method is called whenever the user clicks on this cell in the grid. void GridCell::handleClick() { // When clicked on... if(this->type == DEAD) // If type is DEAD (white), change to LIVE (black). type = LIVE; else type = DEAD; // If type is LIVE (black), change to DEAD (white). setType(type); // Sets new type (color). setType Calls redrawCell() to recolor. } // Method to check cell type and return the color of that type. Qt::GlobalColor GridCell::getColorForCellType() { switch(this->type) { default: case DEAD: return Qt::white; case LIVE: return Qt::black; } } // Helper method. Forces current cell to be redrawn on the GUI. Called whenever the setType method is invoked. void GridCell::redrawCell() { Qt::GlobalColor gc = getColorForCellType(); //Find out what color this cell should be. this->button->setPalette(QPalette(gc,gc)); //Force the button in the cell to be the proper color. this->button->setAutoFillBackground(true); this->button->setFlat(true); //Force QT to NOT draw the borders on the button } Thanks a lot. Let me know if you need anything else.

    Read the article

  • Load binary file using fstream

    - by Kirill V. Lyadvinsky
    I'm trying to load binary file using fstream in the following way: #include <iostream #include <fstream #include <iterator #include <vector using namespace std; int main() { basic_fstream<uint32_t file( "somefile.dat", ios::in|ios::binary ); vector<uint32_t buffer; buffer.assign( istream_iterator<uint32_t, uint32_t( file ), istream_iterator<uint32_t, uint32_t() ); cout << buffer.size() << endl; return 0; } But it doesn't work. In Ubuntu it crashed with std::bad_cast exception. In MSVC++ 2008 it just prints 0. I know that I could use file.read to load file, but I want to use iterator and operator>> to load parts of the file. Is that possible? Why the code above doesn't work?

    Read the article

  • How to add event listners / signals to a simple superman class?

    - by Kabumbus
    I can and would love to use boost or std for this. Sorry - I am new to C++. So I created a really simple program like: #include <iostream> #include <string> using namespace std; class superman { public: string punch(){return cout << "superman: I hit the bad guy!" << endl;}; }; int main() { superman clark; clark.punch(); cin.get(); } I want to add an event listner that would tell me when clark punched and cout something like "superman punched!". How to add such event listner and event function to my class?

    Read the article

  • Problem with istringstream in C++

    - by helixed
    Hello, I'm sure I'm just doing something stupid here, but I can't quite figure out what it is. When I try to run this code: #include <iostream> #include <string> #include <sstream> using namespace std; int main(int argc, char *argv[]) { string s("hello"); istringstream input(s, istringstream::in); string s2; input >> s2; cout << s; } I get this error: malloc: *** error for object 0x100016200: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug The only thing I can think of is that I allocated s2 on the stack, but I thought strings manage their own content on the heap. Any help here would be appreciated. Thanks, helixed

    Read the article

  • XCode newbie: How to find the source code for standard or system libraries?

    - by Jan Hettich
    XCode newbie question here: If I'm programming in C++ or objective C, and I #include or #import a library; e.g. #include <iostream> #import <Cocoa/Cocoa.h> I'm often not sure where to look for these header files in the directory structure on my Mac. In other development environments, you can right click the included or imported filename and have the option to jump to source. Is there such a feature in XCode? Also, for the standard C++ libraries and the Cocoa framework, is the source code for the implementation files available, or only the headers together with compiled link libraries? Thanks!

    Read the article

  • What is the ambiguity in this piece of code?

    - by cambr
    #include <iostream> using namespace std; class A { public: void eat(){ cout<<"A";} }; class B: public A { public: void eat(){ cout<<"B";} }; class C: public A { public: void eat(){ cout<<"C";} }; class D: public B,C { public: void eat(){ cout<<"D";} }; int main(){ A *a = new D(); a->eat(); } I am not sure this is called diamond problem or not, but why doesn't this work? When I said, a->eat() (remember eat() is not virtual), there is only one possible eat() to call, that of A. Why then, do I get this error: 'A' is an ambiguous base of 'D'

    Read the article

  • Error while excuting a simple boost thread program

    - by Eternal Learner
    Hi All, Could you tell mw what is the problem with the below boost::thread program #include<iostream> #include<boost/thread/thread.hpp> boost::mutex mutex; class A { public: A() : a(0) {} void operator()() { boost::mutex::scoped_lock lock(mutex); } private: int a; }; int main() { boost::thread thr1(A()); boost::thread thr2(A()); thr1.join(); thr2.join(); } I get the error message: error: request for member 'join' in 'thr1', which is of non-class type 'boost::thread()(A ()())' BoostThread2.cpp:30: error: request for member 'join' in 'thr2', which is of non-class type 'boost::thread ()(A ()())'

    Read the article

  • Mac OS X 10.9 with GCC 4.7.3, stdlib.h: no such file or directory

    - by Leon Kaihua Li
    I'm doing some development with C++ on Mac OS. The code worked fine on Mac OS 10.8.3/10.8.4, with GCC 4.7.3. However recently I upgraded my OS to Mavericks 10.9 and Xcode 5.0. I find that when I try to compile my code, both gcc/g++/clang responds with: *******.C:1:** stdlib.h:no such file or directory *******.C:2:** iostream.h:no such file or directory Since I'm not familiar with Mac OS(My working platform is openSUSE), what can I do for it? will it help if I install "Command Line Tools" from Xcode? Or is there anyway that I could re-build the include index? Include dir of GCC is /opt/local/include/gcc47 and it seems there is a stdlib.h in it. The path is /opt/local/include/gcc47/c++/tr1/ Please help me, and thank you very much.

    Read the article

  • Singleton code linker errors in vc 9.0. Runs fine in linux compiled with gcc

    - by user306560
    I have a simple logger that is implemented as a singleton. It works like i want when I compile and run it with g++ in linux but when I compile in Visual Studio 9.0 with vc++ I get the following errors. Is there a way to fix this? I don't mind changing the logger class around, but I would like to avoid changing how it is called. 1>Linking... 1>loggerTest.obj : error LNK2005: "public: static class Logger * __cdecl Logger::getInstance(void)" (?getInstance@Logger@@SAPAV1@XZ) already defined in Logger.obj 1>loggerTest.obj : error LNK2005: "public: void __thiscall Logger::log(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (?log@Logger@@QAEXABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) already defined in Logger.obj 1>loggerTest.obj : error LNK2005: "public: void __thiscall Logger::closeLog(void)" (?closeLog@Logger@@QAEXXZ) already defined in Logger.obj 1>loggerTest.obj : error LNK2005: "private: static class Logger * Logger::_instance" (?_instance@Logger@@0PAV1@A) already defined in Logger.obj 1>Logger.obj : error LNK2001: unresolved external symbol "private: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > Logger::_path" (?_path@Logger@@0V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A) 1>loggerTest.obj : error LNK2001: unresolved external symbol "private: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > Logger::_path" (?_path@Logger@@0V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A) 1>Logger.obj : error LNK2001: unresolved external symbol "private: static class boost::mutex Logger::_mutex" (?_mutex@Logger@@0Vmutex@boost@@A) 1>loggerTest.obj : error LNK2001: unresolved external symbol "private: static class boost::mutex Logger::_mutex" (?_mutex@Logger@@0Vmutex@boost@@A) 1>Logger.obj : error LNK2001: unresolved external symbol "private: static class std::basic_ofstream<char,struct std::char_traits<char> > Logger::_log" (?_log@Logger@@0V?$basic_ofstream@DU?$char_traits@D@std@@@std@@A) 1>loggerTest.obj : error LNK2001: unresolved external symbol "private: static class std::basic_ofstream<char,struct std::char_traits<char> > Logger::_log" (?_log@Logger@@0V?$basic_ofstream@DU?$char_traits@D@std@@@std@@A) The code, three files Logger.h Logger.cpp test.cpp #ifndef __LOGGER_CPP__ #define __LOGGER_CPP__ #include "Logger.h" Logger* Logger::_instance = 0; //string Logger::_path = "log"; //ofstream Logger::_log; //boost::mutex Logger::_mutex; Logger* Logger::getInstance(){ { boost::mutex::scoped_lock lock(_mutex); if(_instance == 0) { _instance = new Logger; _path = "log"; } } //mutex return _instance; } void Logger::log(const std::string& msg){ { boost::mutex::scoped_lock lock(_mutex); if(!_log.is_open()){ _log.open(_path.c_str()); } if(_log.is_open()){ _log << msg.c_str() << std::endl; } } } void Logger::closeLog(){ Logger::_log.close(); } #endif ` ... #ifndef __LOGGER_H__ #define __LOGGER_H__ #include <iostream> #include <string> #include <fstream> #include <boost/thread/mutex.hpp> #include <boost/thread.hpp> using namespace std; class Logger { public: static Logger* getInstance(); void log(const std::string& msg); void closeLog(); protected: Logger(){} private: static Logger* _instance; static string _path; static bool _logOpen; static ofstream _log; static boost::mutex _mutex; //check mutable }; #endif test.cpp ` #include <iostream> #include "Logger.cpp" using namespace std; int main(int argc, char *argv[]) { Logger* log = Logger::getInstance(); log->log("hello world\n"); return 0; }

    Read the article

  • Cannot find sleep function

    - by Tyzak
    hello, i'm new at C Programming (i learned c++) i want to create a process with windows.h at first i just want to start my main programm that creates a process ( -- starts an other programm) that's my code, but it doesn't really work, i removed every unnessasery line of code but "void sleep(700)" (or "sleep (700)" for testing if the windows methods work, but i get an error, that "sleep" cant be found. #include <iostream> #include <windows.h> #include <string> using namespace std; void main() { //bool ret; //startupinfo stupinfo; //prozess_information pro2info; //Getstartupinfo (&stupinfo); //createprozess(null, "C:\\bsss10\\betriebssystemePRA1.exe", null, null, false, create_new_console, null, // null, &stupinfo, &pro2info); sleep (700); cout<< "hello"; } thanks in advance

    Read the article

  • C++ destructor seems to be called 'early'

    - by suicideducky
    Please see the "edit" section for the updated information. Sorry for yet another C++ dtor question... However I can't seem to find one exactly like mine as all the others are assigning to STL containers (that will delete objects itself) whereas mine is to an array of pointers. So I have the following code fragment #include<iostream> class Block{ public: int x, y, z; int type; Block(){ x=1; y=2; z=3; type=-1; } }; template <class T> class Octree{ T* children[8]; public: ~Octree(){ for( int i=0; i<8; i++){ std::cout << "del:" << i << std::endl; delete children[i]; } } Octree(){ for( int i=0; i<8; i++ ) children[i] = new T; } // place newchild in array at [i] void set_child(int i, T* newchild){ children[i] = newchild; } // return child at [i] T* get_child(int i){ return children[i]; } // place newchild at [i] and return the old [i] T* swap_child(int i, T* newchild){ T* p = children[i]; children[i] = newchild; return p; } }; int main(){ Octree< Octree<Block> > here; std::cout << "nothing seems to have broken" << std::endl; } Looking through the output I notice that the destructor is being called many times before I think it should (as Octree is still in scope), the end of the output also shows: del:0 del:0 del:1 del:2 del:3 Process returned -1073741819 (0xC0000005) execution time : 1.685 s Press any key to continue. For some reason the destructor is going through the same point in the loop twice (0) and then dying. All of this occures before the "nothing seems to have gone wrong" line which I expected before any dtor was called. Thanks in advance :) EDIT The code I posted has some things removed that I thought were unnecessary but after copying and compiling the code I pasted I no longer get the error. What I removed was other integer attributes of the code. Here is the origional: #include<iostream> class Block{ public: int x, y, z; int type; Block(){ x=1; y=2; z=3; type=-1; } Block(int xx, int yy, int zz, int ty){ x=xx; y=yy; z=zz; type=ty; } Block(int xx, int yy, int zz){ x=xx; y=yy; z=zz; type=0; } }; template <class T> class Octree{ int x, y, z; int size; T* children[8]; public: ~Octree(){ for( int i=0; i<8; i++){ std::cout << "del:" << i << std::endl; delete children[i]; } } Octree(int xx, int yy, int zz, int size){ x=xx; y=yy; z=zz; size=size; for( int i=0; i<8; i++ ) children[i] = new T; } Octree(){ Octree(0, 0, 0, 10); } // place newchild in array at [i] void set_child(int i, T* newchild){ children[i] = newchild; } // return child at [i] T* get_child(int i){ return children[i]; } // place newchild at [i] and return the old [i] T* swap_child(int i, T* newchild){ T* p = children[i]; children[i] = newchild; return p; } }; int main(){ Octree< Octree<Block> > here; std::cout << "nothing seems to have broken" << std::endl; } Also, as for the problems with set_child, get_child and swap_child leading to possible memory leaks this will be solved as a wrapper class will either use get before set or use swap to get the old child and write this out to disk before freeing the memory itself. I am glad that it is not my memory management failing but rather another error. I have not made a copy and/or assignment operator yet as I was just testing the block tree out, I will almost certainly make them all private very soon. This version spits out -1073741819. Thank you all for your suggestions and I apologise for highjacking my own thread :$

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >