Search Results

Search found 1621 results on 65 pages for 'cout'.

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

  • Error inserting data in binary tree

    - by chepe263
    I copied this code (in spanish) http://www.elrincondelc.com/nuevorincon/index.php?pag=codigos&id=4 and wrote a new one. This is my code: #include <cstdlib> #include <conio.h> #include <iostream> using namespace std; struct nodoarbol { int dato; struct nodoarbol *izq; struct nodoarbol *der; }; typedef nodoarbol Nodo; typedef Nodo *Arbol; void insertar(Arbol *, int); void inorden(Arbol); void postorden(Arbol); void preorden(Arbol); void insertar(Arbol *raiz, int nuevo){ if (*raiz==NULL){ *raiz = (Nodo *)malloc(sizeof(Nodo)); if (*raiz != NULL){ (*raiz)->dato=nuevo; (*raiz)->der=NULL; (*raiz)->izq=NULL; } else{ cout<<"No hay memoria suficiente u ocurrio un error"; } } else{ if (nuevo < (*raiz)->dato) insertar( &((*raiz)->izq), nuevo ); else if (nuevo > (*raiz)->dato) insertar(&((*raiz)->der), nuevo); } }//inseertar void inorden(Arbol raiz){ if (raiz != NULL){ inorden(raiz->izq); cout << raiz->dato << " "; inorden(raiz->der); } } void preorden(Arbol raiz){ if (raiz != NULL){ cout<< raiz->dato << " "; preorden(raiz->izq); preorden(raiz->der); } } void postorden(Arbol raiz){ if (raiz!=NULL){ postorden(raiz->izq); postorden(raiz->der); cout<<raiz->dato<<" "; } } int main() { int i; i=0; int val; Arbol raiz = NULL; for (i=0; i<10; i++){ cout<<"Inserte un numero"; cin>>val; insertar( (raiz), val); } cout<<"\nPreorden\n"; preorden(raiz); cout<<"\nIneorden\n"; inorden(raiz); cout<<"\nPostorden\n"; postorden(raiz); return 0; } I'm using netbeans 7.1.1, mingw32 compiler This is the output: make[2]: Leaving directory `/q/netbeans c++/NetBeansProjects/treek' make[1]: Leaving directory `/q/netbeans c++/NetBeansProjects/treek' main.cpp: In function 'int main()': main.cpp:110:30: error: cannot convert 'Arbol {aka nodoarbol*}' to 'Nodo** {aka nodoarbol**}' for argument '1' to 'void insertar(Nodo**, int)' make[2]: *** [build/Release/MinGW-Windows/main.o] Error 1 make[1]: *** [.build-conf] Error 2 make: *** [.build-impl] Error 2 BUILD FAILED (exit value 2, total time: 11s) I don't understand what's wrong since i just copied the code (and rewrite it to my own code). I'm really good in php, asp.net (vb) and other languages but c is a headche for me. I've been struggling with this problem for about an hour. Could somebody tell me what could it be?

    Read the article

  • C++ function will not return

    - by Mike
    I have a function that I am calling that runs all the way up to where it should return but doesn't return. If I cout something for debugging at the very end of the function, it gets displayed but the function does not return. fetchData is the function I am referring to. It gets called by outputFile. cout displays "done here" but not "data fetched" I know this code is messy but can anyone help me figure this out? Thanks //Given an inode return all data of i_block data char* fetchData(iNode tempInode){ char* data; data = new char[tempInode.i_size]; this->currentInodeSize = tempInode.i_size; //Loop through blocks to retrieve data vector<unsigned int> i_blocks; i_blocks.reserve(tempInode.i_blocks); this->currentDataPosition = 0; cout << "currentDataPosition set to 0" << std::endl; cout << "i_blocks:" << tempInode.i_blocks << std::endl; int i = 0; for(i = 0; i < 12; i++){ if(tempInode.i_block[i] == 0) break; i_blocks.push_back(tempInode.i_block[i]); } appendIndirectData(tempInode.i_block[12], &i_blocks); appendDoubleIndirectData(tempInode.i_block[13], &i_blocks); appendTripleIndirectData(tempInode.i_block[14], &i_blocks); //Loop through all the block addresses to get the actual data for(i=0; i < i_blocks.size(); i++){ appendData(i_blocks[i], data); } cout << "done here" << std::endl; return data; } void appendData(int block, char* data){ char* tempBuffer; tempBuffer = new char[this->blockSize]; ifstream file (this->filename, std::ios::binary); int entryLocation = block*this->blockSize; file.seekg (entryLocation, ios::beg); file.read(tempBuffer, this->blockSize); //Append this block to data for(int i=0; i < this->blockSize; i++){ data[this->currentDataPosition] = tempBuffer[i]; this->currentDataPosition++; } data[this->currentDataPosition] = '\0'; } void outputFile(iNode file, string filename){ char* data; cout << "File Transfer Started" << std::endl; data = this->fetchData(file); cout << "data fetched" << std::endl; char *outputFile = (char*)filename.c_str(); ofstream myfile; myfile.open (outputFile,ios::out|ios::binary); int i = 0; for(i=0; i < file.i_size; i++){ myfile << data[i]; } myfile.close(); cout << "File Transfer Completed" << std::endl; return; }

    Read the article

  • count specific things within a code in c++

    - by shap
    can anyone help me make this more generalised and more pro? #include <fstream> #include <iostream> #include <string> #include <vector> using namespace std; int main() { // open text file for input: string file_name; cout << "please enter file name: "; cin >> file_name; // associate the input file stream with a text file ifstream infile(file_name.c_str()); // error checking for a valid filename if ( !infile ) { cerr << "Unable to open file " << file_name << " -- quitting!\n"; return( -1 ); } else cout << "\n"; // some data structures to perform the function vector<string> lines_of_text; string textline; // read in text file, line by while (getline( infile, textline, '\n' )) { // add the new element to the vector lines_of_text.push_back( textline ); // print the 'back' vector element - see the STL documentation cout << lines_of_text.back() << "\n"; } cout<<"OUTPUT BEGINS HERE: "<<endl<<endl; cout<<"the total capacity of vector: lines_of_text is: "<<lines_of_text.capacity()<<endl; int PLOC = (lines_of_text.size()+1); int numbComments =0; int numbClasses =0; cout<<"\nThe total number of physical lines of code is: "<<PLOC<<endl; for (int i=0; i<(PLOC-1); i++) //reads through each part of the vector string line-by-line and triggers if the //it registers the "//" which will output a number lower than 100 (since no line is 100 char long and if the function does not //register that character within the string, it outputs a public status constant that is found in the class string and has a huge value //alot more than 100. { string temp(lines_of_text [i]); if (temp.find("//")<100) numbComments +=1; } cout<<"The total number of comment lines is: "<<numbComments<<endl; for (int j=0; j<(PLOC-1); j++) { string temp(lines_of_text [j]); if (temp.find("};")<100) numbClasses +=1; } cout<<"The total number of classes is: "<<numbClasses<<endl;

    Read the article

  • multimap erase doesnt work

    - by nikiforzx6r
    following code doensnt work with input: 2 7 add Elly 0888424242 add Elly 0883666666 queryname Elly querynum 0883266642 querynum 0888424242 delnum 0883666666 queryname Elly 3 add Kriss 42 add Elly 42 querynum 42 Why my erase doesnt work? #include<stdio.h> #include<iostream> #include<map> #include <string> using namespace std; void PrintMapName(multimap<string, string> pN, string s) { pair<multimap<string,string>::iterator, multimap<string,string>::iterator> ii; multimap<string, string>::iterator it; ii = pN.equal_range(s); multimap<string, int> tmp; for(it = ii.first; it != ii.second; ++it) { tmp.insert(pair<string,int>(it->second,1)); } multimap<string, int>::iterator i; bool flag = false; for(i = tmp.begin(); i != tmp.end(); i++) { if(flag) { cout<<" "; } cout<<i->first; if(flag) { cout<<" "; } flag = true; } cout<<endl; } void PrintMapNumber(multimap<string, string> pN, string s) { multimap<string, string>::iterator it; multimap<string, int> tmp; for(it = pN.begin(); it != pN.end(); it++ ) { if(it->second == s) { tmp.insert(pair<string,int>(it->first,1)); } } multimap<string, int>::iterator i; bool flag = false; for(i = tmp.begin(); i != tmp.end(); i++) { if(flag) { cout<<" "; } cout<<i->first; if(flag) { cout<<" "; } flag = true; } cout<<endl; } void PrintFull(multimap<string, string> pN) { multimap<string, string>::iterator it; for(it = pN.begin(); it != pN.end(); it++ ) { cout<<"Key = "<<it->first<<" Value = "<<it->second<<endl; } } int main() { multimap<string, string> phoneNums; int N; cin>>N; int tests; string tmp, tmp1,tmp2; while(N > 0) { cin>>tests; while(tests > 0) { cin>>tmp; if(tmp == "add") { cin>>tmp1>>tmp2; phoneNums.insert(pair<string,string>(tmp1,tmp2)); } else { if(tmp == "delnum") { /////////////////////////////////////////HEREEEEEEE multimap<string, string>::iterator it; multimap<string, string>::iterator tmpr; for(it = phoneNums.begin(); it != phoneNums.end();) { tmpr = it; if(it->second == tmp1) { ++tmpr; if(tmpr == phoneNums.end()) { phoneNums.erase(it,tmpr); break; } else { phoneNums.erase(it,tmpr); } } } } else { if(tmp == "delname") { cin>>tmp1; phoneNums.erase(tmp1); } else { if(tmp =="queryname") { cin>>tmp1; PrintMapName(phoneNums, tmp1); } else//querynum { cin>>tmp1; PrintMapNumber(phoneNums, tmp1); } } } } tests--; } N--; } return 0; }

    Read the article

  • How would you go about tackling this problem? [SOLVED in C++]

    - by incrediman
    Intro: EDIT: See solution at the bottom of this question (c++) I have a programming contest coming up in about half a week, and I've been prepping :) I found a bunch of questions from this canadian competition, they're great practice: http://cemc.math.uwaterloo.ca/contests/computing/2009/stage2/day1.pdf I'm looking at problem B ("Dinner"). Any idea where to start? I can't really think of anything besides the naive approach (ie. trying all permutations) which would take too long to be a valid answer. Btw, the language there says c++ and pascal I think, but i don't care what language you use - I mean really all I want is a hint as to the direction I should proceed in, and perhpas a short explanation to go along with it. It feels like I'm missing something obvious... Of course extended speculation is more than welcome, but I just wanted to clarify that I'm not looking for a full solution here :) Short version of the question: You have a binary string N of length 1-100 (in the question they use H's and G's instead of one's and 0's). You must remove all of the digits from it, in the least number of steps possible. In each step you may remove any number of adjacent digits so long as they are the same. That is, in each step you can remove any number of adjacent G's, or any number of adjacent H's, but you can't remove H's and G's in one step. Example: HHHGHHGHH Solution to the example: 1. HHGGHH (remove middle Hs) 2. HHHH (remove middle Gs) 3. Done (remove Hs) -->Would return '3' as the answer. Note that there can also be a limit placed on how large adjacent groups have to be when you remove them. For example it might say '2', and then you can't remove single digits (you'd have to remove pairs or larger groups at a time). Solution I took Mark Harrison's main algorithm, and Paradigm's grouping idea and used them to create the solution below. You can try it out on the official test cases if you want. //B.cpp //include debug messages? #define DEBUG false #include <iostream> #include <stdio.h> #include <vector> using namespace std; #define FOR(i,n) for (int i=0;i<n;i++) #define FROM(i,s,n) for (int i=s;i<n;i++) #define H 'H' #define G 'G' class String{ public: int num; char type; String(){ type=H; num=0; } String(char type){ this->type=type; num=1; } }; //n is the number of bits originally in the line //k is the minimum number of people you can remove at a time //moves is the counter used to determine how many moves we've made so far int n, k, moves; int main(){ /*Input from File*/ scanf("%d %d",&n,&k); char * buffer = new char[200]; scanf("%s",buffer); /*Process input into a vector*/ //the 'line' is a vector of 'String's (essentially contigious groups of identical 'bits') vector<String> line; line.push_back(String()); FOR(i,n){ //if the last String is of the correct type, simply increment its count if (line.back().type==buffer[i]) line.back().num++; //if the last String is of the wrong type but has a 0 count, correct its type and set its count to 1 else if (line.back().num==0){ line.back().type=buffer[i]; line.back().num=1; } //otherwise this is the beginning of a new group, so create the new group at the back with the correct type, and a count of 1 else{ line.push_back(String(buffer[i])); } } /*Geedily remove groups until there are at most two groups left*/ moves=0; int I;//the position of the best group to remove int bestNum;//the size of the newly connected group the removal of group I will create while (line.size()>2){ /*START DEBUG*/ if (DEBUG){ cout<<"\n"<<moves<<"\n----\n"; FOR(i,line.size()) printf("%d %c \n",line[i].num,line[i].type); cout<<"----\n"; } /*END DEBUG*/ I=1; bestNum=-1; FROM(i,1,line.size()-1){ if (line[i-1].num+line[i+1].num>bestNum && line[i].num>=k){ bestNum=line[i-1].num+line[i+1].num; I=i; } } //remove the chosen group, thus merging the two adjacent groups line[I-1].num+=line[I+1].num; line.erase(line.begin()+I);line.erase(line.begin()+I); moves++; } /*START DEBUG*/ if (DEBUG){ cout<<"\n"<<moves<<"\n----\n"; FOR(i,line.size()) printf("%d %c \n",line[i].num,line[i].type); cout<<"----\n"; cout<<"\n\nFinal Answer: "; } /*END DEBUG*/ /*Attempt the removal of the last two groups, and output the final result*/ if (line.size()==2 && line[0].num>=k && line[1].num>=k) cout<<moves+2;//success else if (line.size()==1 && line[0].num>=k) cout<<moves+1;//success else cout<<-1;//not everyone could dine. /*START DEBUG*/ if (DEBUG){ cout<<" moves."; } /*END DEBUG*/ }

    Read the article

  • program not working as expected!

    - by wilson88
    Can anyone just help spot why my program is not returning the expected output.related to my previous question.Am passing a vector by refrence, I want to see whats in the container before I copy them to another loaction.if u remove comments on loadRage, u will see bids are generated by the trader. #include <iostream> #include <vector> #include <string> #include <algorithm> #include <cstdlib> #include <iomanip> using namespace std; const int NUMSELLER = 1; const int NUMBUYER = 1; const int NUMBIDS = 20; const int MINQUANTITY = 1; const int MAXQUANTITY = 30; const int MINPRICE =100; const int MAXPRICE = 150; int s=0; int trdId; // Bid, simple container for values struct Bid { int bidId, trdId, qty, price; char type; // for sort and find. bool operator<(const Bid &other) const { return price < other.price; } bool operator==(int bidId) const { return this->bidId == bidId; } }; // alias to the list, make type consistent typedef vector<Bid> BidList; // this class generates bids! class Trader { private: int nextBidId; public: Trader(); Bid getNextBid(); Bid getNextBid(char type); // generate a number of bids void loadRange(BidList &, int size); void loadRange(BidList &, char type, int size); void setVector(); }; Trader::Trader() : nextBidId(1) {} #define RAND_RANGE(min, max) ((rand() % (max-min+1)) + min) Bid Trader::getNextBid() { char type = RAND_RANGE('A','B'); return getNextBid(type); } Bid Trader::getNextBid(char type) { for(int i = 0; i < NUMSELLER+NUMBUYER; i++) { // int trdId = RAND_RANGE(1,9); if (s<10){trdId=0;type='A';} else {trdId=1;type='B';} s++; int qty = RAND_RANGE(MINQUANTITY, MAXQUANTITY); int price = RAND_RANGE(MINPRICE, MAXPRICE); Bid bid = {nextBidId++, trdId, qty, price, type}; return bid; } } //void Trader::loadRange(BidList &list, int size) { // for (int i=0; i<size; i++) { list.push_back(getNextBid()); } //} // //void Trader::loadRange(BidList &list, char type, int size) { // for (int i=0; i<size; i++) { list.push_back(getNextBid(type)); } //} //---------------------------AUCTIONEER------------------------------------------- class Auctioneer { vector<Auctioneer> List; Trader trader; vector<Bid> list; public: Auctioneer(){}; void accept_bids(const BidList& bid); }; typedef vector<Auctioneer*> bidlist; void Auctioneer::accept_bids(const BidList& bid){ BidList list; //copy (BidList.begin(),BidList.end(),list); } //all the happy display commands void show(const Bid &bid) { cout << "\tBid\t(" << setw(3) << bid.bidId << "\t " << setw(3) << bid.trdId << "\t " << setw(3) << bid.type <<"\t " << setw(3) << bid.qty <<"\t " << setw(3) << bid.price <<")\t\n " ; } void show(const BidList &list) { cout << "\t\tBidID | TradID | Type | Qty | Price \n\n"; for(BidList::const_iterator itr=list.begin(); itr != list.end(); ++itr) { //cout <<"\t\t"; show(*itr); cout << endl; } cout << endl; } //search now checks for failure void show(const char *msg, const BidList &list) { cout << msg << endl; show(list); } void searchTest(BidList &list, int bidId) { cout << "Searching for Bid " << bidId << endl; BidList::const_iterator itr = find(list.begin(), list.end(), bidId); if (itr==list.end()) { cout << "Bid not found."; } else { cout << "Bid has been found. Its : "; show(*itr); } cout << endl; } //comparator function for price: returns true when x belongs before y bool compareBidList(Bid one, Bid two) { if (one.type == 'A' && two.type == 'B') return (one.price < two.price); return false; } void sort(BidList &bidlist) { sort(bidlist.begin(), bidlist.end(), compareBidList); } int main(int argc, char **argv) { Trader trader; BidList bidlist; Auctioneer auctioneer; //bidlist list; auctioneer.accept_bids(bidlist); //trader.loadRange(bidlist, NUMBIDS); show("Bids before sort:", bidlist); sort(bidlist); show("Bids after sort:", bidlist); system("pause"); return 0; }

    Read the article

  • Steganography : Encoded audio and video file not being played, getting corrupted. What is the issue

    - by Shantanu Gupta
    I have made a steganography program to encrypt/Decrypt some text under image audio and video. I used image as bmp(54 byte header) file, audio as wav(44 byte header) file and video as avi(56 byte header) file formats. When I tries to encrypt text under all these file then it gets encrypted successfully and are also getting decrypted correctly. But it is creating a problem with audio and video i.e these files are not being played after encrypted result. What can be the problem. I am working on Turbo C++ compiler. I know it is super outdated compiler but I have to do it in this only. Here is my code to encrypt. int Binary_encode(char *txtSourceFileName, char *binarySourceFileName, char *binaryTargetFileName,const short headerSize) { long BinarySourceSize=0,TextSourceSize=0; char *Buffer; long BlockSize=10240, i=0; ifstream ReadTxt, ReadBinary; //reads ReadTxt.open(txtSourceFileName,ios::binary|ios::in);//file name, mode of open, here input mode i.e. read only if(!ReadTxt) { cprintf("\nFile can not be opened."); return 0; } ReadBinary.open(binarySourceFileName,ios::binary|ios::in);//file name, mode of open, here input mode i.e. read only if(!ReadBinary) { ReadTxt.close();//closing opened file cprintf("\nFile can not be opened."); return 0; } ReadBinary.seekg(0,ios::end);//setting pointer to a file at the end of file. ReadTxt.seekg(0,ios::end); BinarySourceSize=(long )ReadBinary.tellg(); //returns the position of pointer TextSourceSize=(long )ReadTxt.tellg(); //returns the position of pointer ReadBinary.seekg(0,ios::beg); //sets the pointer to the begining of file ReadTxt.seekg(0,ios::beg); //sets the pointer to the begining of file if(BinarySourceSize<TextSourceSize*50) //Minimum size of an image should be 50 times the size of file to be encrypted { cout<<"\n\n"; cprintf("Binary File size should be bigger than text file size."); ReadBinary.close(); ReadTxt.close(); return 0; } cout<<"\n"; cprintf("\n\nSize of Source Image/Audio File is : "); cout<<(float)BinarySourceSize/1024; cprintf("KB"); cout<<"\n"; cprintf("Size of Text File is "); cout<<TextSourceSize; cprintf(" Bytes"); cout<<"\n"; getch(); //write header to file without changing else file will not open //bmp image's header size is 53 bytes Buffer=new char[headerSize]; ofstream WriteBinary; // writes to file WriteBinary.open(binaryTargetFileName,ios::binary|ios::out|ios::trunc);//file will be created or truncated if already exists ReadBinary.read(Buffer,headerSize);//reads no of bytes and stores them into mem, size contains no of bytes in a file WriteBinary.write(Buffer,headerSize);//writes header to 2nd image delete[] Buffer;//deallocate memory /* Buffer = new char[sizeof(long)]; Buffer = (char *)(&TextSourceSize); cout<<Buffer; */ WriteBinary.write((char *)(&TextSourceSize),sizeof(long)); //writes no of byte to be written in image immediate after header ends //to decrypt file if(!(Buffer=new char[TextSourceSize])) { cprintf("Enough Memory could not be assigned."); return 0; } ReadTxt.read(Buffer,TextSourceSize);//read all data from text file ReadTxt.close();//file no more needed WriteBinary.write(Buffer,TextSourceSize);//writes all text file data into image delete[] Buffer;//deallocate memory //replace Tsize+1 below with Tsize and run the program to see the change //this is due to the reason that 50-54 byte no are of colors which we will be changing ReadBinary.seekg(TextSourceSize+1,ios::cur);//move pointer to the location-current loc i.e. 53+content of text file //write remaining image content to image file while(i<BinarySourceSize-headerSize-TextSourceSize+1) { i=i+BlockSize; Buffer=new char[BlockSize]; ReadBinary.read(Buffer,BlockSize);//reads no of bytes and stores them into mem, size contains no of bytes in a file WriteBinary.write(Buffer,BlockSize); delete[] Buffer; //clear memory, else program can fail giving correct output } ReadBinary.close(); WriteBinary.close(); //Encoding Completed return 0; } Code to decrypt int Binary_decode(char *binarySourceFileName, char *txtTargetFileName, const short headerSize) { long TextDestinationSize=0; char *Buffer; long BlockSize=10240; ifstream ReadBinary; ofstream WriteText; ReadBinary.open(binarySourceFileName,ios::binary|ios::in);//file will be appended if(!ReadBinary) { cprintf("File can not be opened"); return 0; } ReadBinary.seekg(headerSize,ios::beg); Buffer=new char[4]; ReadBinary.read(Buffer,4); TextDestinationSize=*((long *)Buffer); delete[] Buffer; cout<<"\n\n"; cprintf("Size of the File that will be created is : "); cout<<TextDestinationSize; cprintf(" Bytes"); cout<<"\n\n"; sleep(1); WriteText.open(txtTargetFileName,ios::binary|ios::out|ios::trunc);//file will be created if not exists else truncate its data while(TextDestinationSize>0) { if(TextDestinationSize<BlockSize) BlockSize=TextDestinationSize; Buffer= new char[BlockSize]; ReadBinary.read(Buffer,BlockSize); WriteText.write(Buffer,BlockSize); delete[] Buffer; TextDestinationSize=TextDestinationSize-BlockSize; } ReadBinary.close(); WriteText.close(); return 0; } int text_encode(char *SourcefileName, char *DestinationfileName) { ifstream fr; //reads ofstream fw; // writes to file char c; int random; clrscr(); fr.open(SourcefileName,ios::binary);//file name, mode of open, here input mode i.e. read only if(!fr) { cprintf("File can not be opened."); getch(); return 0; } fw.open(DestinationfileName,ios::binary|ios::out|ios::trunc);//file will be created or truncated if already exists while(fr) { int i; while(fr!=0) { fr.get(c); //reads a character from file and increments its pointer char ch; ch=c; ch=ch+1; fw<<ch; //appends character in c to a file } } fr.close(); fw.close(); return 0; } int text_decode(char *SourcefileName, char *DestinationName) { ifstream fr; //reads ofstream fw; // wrrites to file char c; int random; clrscr(); fr.open(SourcefileName,ios::binary);//file name, mode of open, here input mode i.e. read only if(!fr) { cprintf("File can not be opened."); return 0; } fw.open(DestinationName,ios::binary|ios::out|ios::trunc);//file will be created or truncated if already exists while(fr) { int i; while(fr!=0) { fr.get(c); //reads a character from file and increments its pointer char ch; ch=c; ch=ch-1; fw<<ch; //appends character in c to a file } } fr.close(); fw.close(); return 0; }

    Read the article

  • g++ SSE intrinsics dilemma - value from intrinsic "saturates"

    - by Sriram
    Hi, I wrote a simple program to implement SSE intrinsics for computing the inner product of two large (100000 or more elements) vectors. The program compares the execution time for both, inner product computed the conventional way and using intrinsics. Everything works out fine, until I insert (just for the fun of it) an inner loop before the statement that computes the inner product. Before I go further, here is the code: //this is a sample Intrinsics program to compute inner product of two vectors and compare Intrinsics with traditional method of doing things. #include <iostream> #include <iomanip> #include <xmmintrin.h> #include <stdio.h> #include <time.h> #include <stdlib.h> using namespace std; typedef float v4sf __attribute__ ((vector_size(16))); double innerProduct(float* arr1, int len1, float* arr2, int len2) { //assume len1 = len2. float result = 0.0; for(int i = 0; i < len1; i++) { for(int j = 0; j < len1; j++) { result += (arr1[i] * arr2[i]); } } //float y = 1.23e+09; //cout << "y = " << y << endl; return result; } double sse_v4sf_innerProduct(float* arr1, int len1, float* arr2, int len2) { //assume that len1 = len2. if(len1 != len2) { cout << "Lengths not equal." << endl; exit(1); } /*steps: * 1. load a long-type (4 float) into a v4sf type data from both arrays. * 2. multiply the two. * 3. multiply the same and store result. * 4. add this to previous results. */ v4sf arr1Data, arr2Data, prevSums, multVal, xyz; //__builtin_ia32_xorps(prevSums, prevSums); //making it equal zero. //can explicitly load 0 into prevSums using loadps or storeps (Check). float temp[4] = {0.0, 0.0, 0.0, 0.0}; prevSums = __builtin_ia32_loadups(temp); float result = 0.0; for(int i = 0; i < (len1 - 3); i += 4) { for(int j = 0; j < len1; j++) { arr1Data = __builtin_ia32_loadups(&arr1[i]); arr2Data = __builtin_ia32_loadups(&arr2[i]); //store the contents of two arrays. multVal = __builtin_ia32_mulps(arr1Data, arr2Data); //multiply. xyz = __builtin_ia32_addps(multVal, prevSums); prevSums = xyz; } } //prevSums will hold the sums of 4 32-bit floating point values taken at a time. Individual entries in prevSums also need to be added. __builtin_ia32_storeups(temp, prevSums); //store prevSums into temp. cout << "Values of temp:" << endl; for(int i = 0; i < 4; i++) cout << temp[i] << endl; result += temp[0] + temp[1] + temp[2] + temp[3]; return result; } int main() { clock_t begin, end; int length = 100000; float *arr1, *arr2; double result_Conventional, result_Intrinsic; // printStats("Allocating memory."); arr1 = new float[length]; arr2 = new float[length]; // printStats("End allocation."); srand(time(NULL)); //init random seed. // printStats("Initializing array1 and array2"); begin = clock(); for(int i = 0; i < length; i++) { // for(int j = 0; j < length; j++) { // arr1[i] = rand() % 10 + 1; arr1[i] = 2.5; // arr2[i] = rand() % 10 - 1; arr2[i] = 2.5; // } } end = clock(); cout << "Time to initialize array1 and array2 = " << ((double) (end - begin)) / CLOCKS_PER_SEC << endl; // printStats("Finished initialization."); // printStats("Begin inner product conventionally."); begin = clock(); result_Conventional = innerProduct(arr1, length, arr2, length); end = clock(); cout << "Time to compute inner product conventionally = " << ((double) (end - begin)) / CLOCKS_PER_SEC << endl; // printStats("End inner product conventionally."); // printStats("Begin inner product using Intrinsics."); begin = clock(); result_Intrinsic = sse_v4sf_innerProduct(arr1, length, arr2, length); end = clock(); cout << "Time to compute inner product with intrinsics = " << ((double) (end - begin)) / CLOCKS_PER_SEC << endl; //printStats("End inner product using Intrinsics."); cout << "Results: " << endl; cout << " result_Conventional = " << result_Conventional << endl; cout << " result_Intrinsics = " << result_Intrinsic << endl; return 0; } I use the following g++ invocation to build this: g++ -W -Wall -O2 -pedantic -march=i386 -msse intrinsics_SSE_innerProduct.C -o innerProduct Each of the loops above, in both the functions, runs a total of N^2 times. However, given that arr1 and arr2 (the two floating point vectors) are loaded with a value 2.5, the length of the array is 100,000, the result in both cases should be 6.25e+10. The results I get are: Results: result_Conventional = 6.25e+10 result_Intrinsics = 5.36871e+08 This is not all. It seems that the value returned from the function that uses intrinsics "saturates" at the value above. I tried putting other values for the elements of the array and different sizes too. But it seems that any value above 1.0 for the array contents and any size above 1000 meets with the same value we see above. Initially, I thought it might be because all operations within SSE are in floating point, but floating point should be able to store a number that is of the order of e+08. I am trying to see where I could be going wrong but cannot seem to figure it out. I am using g++ version: g++ (GCC) 4.4.1 20090725 (Red Hat 4.4.1-2). Any help on this is most welcome. Thanks, Sriram.

    Read the article

  • Conway's Game of Life - C++ and Qt

    - by Jeff Bridge
    I've done all of the layouts and have most of the code written even. But, I'm stuck in two places. 1) I'm not quite sure how to set up the timer. Am I using it correctly in the gridwindow class? And, am I used the timer functions/signals/slots correctly with the other gridwindow functions. 2) In GridWindow's timerFired() function, I'm having trouble checking/creating the vector-vectors. I wrote out in the comments in that function exactly what I am trying to do. Any help would be much appreciated. main.cpp // Main file for running the grid window application. #include <QApplication> #include "gridwindow.h" //#include "timerwindow.h" #include <stdexcept> #include <string> #include <fstream> #include <sstream> #include <iostream> void Welcome(); // Welcome Function - Prints upon running program; outputs program name, student name/id, class section. void Rules(); // Rules Function: Prints the rules for Conway's Game of Life. using namespace std; // A simple main method to create the window class and then pop it up on the screen. int main(int argc, char *argv[]) { Welcome(); // Calls Welcome function to print student/assignment info. Rules(); // Prints Conway's Game Rules. QApplication app(argc, argv); // Creates the overall windowed application. int rows = 25, cols = 35; //The number of rows & columns in the game grid. GridWindow widget(NULL,rows,cols); // Creates the actual window (for the grid). widget.show(); // Shows the window on the screen. return app.exec(); // Goes into visual loop; starts executing GUI. } // Welcome Function: Prints my name/id, my class number, the assignment, and the program name. void Welcome() { cout << endl; cout << "-------------------------------------------------------------------------------------------------" << endl; cout << "Name/ID - Gabe Audick #7681539807" << endl; cout << "Class/Assignment - CSCI-102 Disccusion 29915: Homework Assignment #4" << endl; cout << "-------------------------------------------------------------------------------------------------" << endl << endl; } // Rules Function: Prints the rules for Conway's Game of Life. void Rules() { cout << "Welcome to Conway's Game of Life." << endl; cout << "Game Rules:" << endl; cout << "\t 1) Any living cell with fewer than two living neighbours dies, as if caused by underpopulation." << endl; cout << "\t 2) Any live cell with more than three live neighbours dies, as if by overcrowding." << endl; cout << "\t 3) Any live cell with two or three live neighbours lives on to the next generation." << endl; cout << "\t 4) Any dead cell with exactly three live neighbours becomes a live cell." << endl << endl; cout << "Enjoy." << endl << endl; } gridcell.h // A header file for a class representing a single cell in a grid of cells. #ifndef GRIDCELL_H_ #define GRIDCELL_H_ #include <QPalette> #include <QColor> #include <QPushButton> #include <Qt> #include <QWidget> #include <QFrame> #include <QHBoxLayout> #include <iostream> // An enum representing the two different states a cell can have. enum CellType { DEAD, // DEAD = Dead Cell. --> Color = White. LIVE // LIVE = Living Cell. ---> Color = White. }; /* Class: GridCell. A class representing a single cell in a grid. Each cell is implemented as a QT QFrame that contains a single QPushButton. The button is sized so that it takes up the entire frame. Each cell also keeps track of what type of cell it is based on the CellType enum. */ class GridCell : public QFrame { Q_OBJECT // Macro allowing us to have signals & slots on this object. private: QPushButton* button; // The button inside the cell that gives its clickability. CellType type; // The type of cell (DEAD or LIVE.) public slots: void handleClick(); // Callback for handling a click on the current cell. void setType(CellType type); // Cell type mutator. Calls the "redrawCell" function. signals: void typeChanged(CellType type); // Signal to notify listeners when the cell type has changed. public: GridCell(QWidget *parent = NULL); // Constructor for creating a cell. Takes parent widget or default parent to NULL. virtual ~GridCell(); // Destructor. void redrawCell(); // Redraws cell: Sets new type/color. CellType getType() const; //Simple getter for the cell type. private: Qt::GlobalColor getColorForCellType(); // Helper method. Returns color that cell should be based from its value. }; #endif gridcell.cpp #include <iostream> #include "gridcell.h" #include "utility.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(); } // 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 } gridwindow.h // A header file for a QT window that holds a grid of cells. #ifndef GRIDWINDOW_H_ #define GRIDWINDOW_H_ #include <vector> #include <QWidget> #include <QTimer> #include <QGridLayout> #include <QLabel> #include <QApplication> #include "gridcell.h" /* class GridWindow: This is the class representing the whole window that comes up when this program runs. It contains a header section with a title, a middle section of MxN cells and a bottom section with buttons. */ class GridWindow : public QWidget { Q_OBJECT // Macro to allow this object to have signals & slots. private: std::vector<std::vector<GridCell*> > cells; // A 2D vector containing pointers to all the cells in the grid. QLabel *title; // A pointer to the Title text on the window. QTimer *timer; // Creates timer object. public slots: void handleClear(); // Handler function for clicking the Clear button. void handleStart(); // Handler function for clicking the Start button. void handlePause(); // Handler function for clicking the Pause button. void timerFired(); // Method called whenever timer fires. public: GridWindow(QWidget *parent = NULL,int rows=3,int cols=3); // Constructor. virtual ~GridWindow(); // Destructor. std::vector<std::vector<GridCell*> >& getCells(); // Accessor for the array of grid cells. private: QHBoxLayout* setupHeader(); // Helper function to construct the GUI header. QGridLayout* setupGrid(int rows,int cols); // Helper function to constructor the GUI's grid. QHBoxLayout* setupButtonRow(); // Helper function to setup the row of buttons at the bottom. }; #endif gridwindow.cpp #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) { 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(handleClear())); buttonRow->addWidget(clearButton); // 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(handleStart())); 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())); buttonRow->addWidget(pauseButton); // Quit Button - Exits program. QPushButton *quitButton = new QPushButton("EXIT"); quitButton->setFixedSize(100,25); connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit())); 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++) { 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() { 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() { this->timer->stop(); // Stops the timer. delete this->timer; // Deletes timer. } // Accessor method - Gets the 2D vector of grid cells. std::vector<std::vector<GridCell*> >& GridWindow::getCells() { return this->cells; } void GridWindow::timerFired() { // I'm not sure how to write this code. // I want to take the original vector-vector, and also make a new, empty vector-vector of the same size. // I would then go through the code below with the original vector, and apply the rules to the new vector-vector. // Finally, I would make the new vector-vecotr the original vector-vector. (That would be one step in the simulation.) cout << cells[1][2]; /* for (unsigned int m = 0; m < original.size(); m++) { for (unsigned int n = 0; n < original.at(m).size(); n++) { unsigned int neighbors = 0; //Begin counting number of neighbors. if (original[m-1][n-1].getType() == LIVE) // If a cell next to [i][j] is LIVE, add one to the neighbor count. neighbors += 1; if (original[m-1][n].getType() == LIVE) neighbors += 1; if (original[m-1][n+1].getType() == LIVE) neighbors += 1; if (original[m][n-1].getType() == LIVE) neighbors += 1; if (original[m][n+1].getType() == LIVE) neighbors += 1; if (original[m+1][n-1].getType() == LIVE) neighbors += 1; if (original[m+1][n].getType() == LIVE) neighbors += 1; if (original[m+1][n+1].getType() == LIVE) neighbors += 1; if (original[m][n].getType() == LIVE && neighbors < 2) // Apply game rules to cells: Create new, updated grid with the roundtwo vector. roundtwo[m][n].setType(LIVE); else if (original[m][n].getType() == LIVE && neighbors > 3) roundtwo[m][n].setType(DEAD); else if (original[m][n].getType() == LIVE && (neighbors == 2 || neighbors == 3)) roundtwo[m][n].setType(LIVE); else if (original[m][n].getType() == DEAD && neighbors == 3) roundtwo[m][n].setType(LIVE); } }*/ }

    Read the article

  • How to enable rgb colored output in terminal?

    - by t.pimentel
    I'm trying to print a colored string to a gnome-terminal using ANSI escape codes, but, although it works for the custom colors, or even the 256 extra color, it doesn't work with RGB codes. So, simplifying: cout << "\033[33m" << '.' << "\033[0m"; # prints with color cout << "\033[38;5;135m" << '.' << "\033[0m"; # prints with color cout << "\033[38;2;0;135;0m" << '.' << "\033[0m"; # doesn't work, prints with default color How can I output something with an RGB color code in the gnome-terminal? I'm following this link for outputs: Wikipedia ANSI escape code.

    Read the article

  • Order of executions in C++ streams

    - by Krzysztof Bzowski
    It is obvious that first cout prints 7 7 but why the second one prints 8 8 7 ? Why not 7 8 8? How does such constructions work in c++? int ink(int *x){ *x += 1; return *x; } int main(){ int *a; int b = 6; a = &b; cout << ++b << " " << b << endl; cout << b << " " << ink(a) << " " << b; return 0; }

    Read the article

  • iPhone Store Kit returning invalid product ID errors

    - by EToreo
    Hello, I am trying to test In App Purchases on my iPhone and running into a problem where the product IDs I request information for end up being returned to me as invalid product IDs in the "didRecieveResponse" method. I have: Created an in store product associated with this app. It's bundle ID matches everything else. It has been cleared for sale and approved by the developer. Made sure my new provisioning profile has in store app purchases enabled and it has the full app name: "com.domain.appname" Made sure this is the provisioning profile being used to sign the app to my iPhone. Made sure that "com.domain.appname" is the app ID used to build the provisioning profile. Made sure that "com.domain.appname" is used in my plist file as the bundle identifier. Everything seems to be in place, however I still get my products returned to me as invalid IDs. This is the code I am using: - (void)requestProductData { SKProductRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers: [NSSet setWithObject: @"com.domain.appname.productid"]]; request.delegate = self; [request start]; } - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response { NSArray *myProducts = response.products; NSArray *myInvalidProducts = response.invalidProductIdentifiers; for(int i = 1; i < myInvalidProducts.count; ++i) { std::cout <<"invalid product id = " << [[myInvalidProducts objectAtIndex:i] UTF8String] << std::endl; } for(int i = 0; i < myProducts.count; ++i) { SKProduct * myProduct = [myProducts objectAtIndex:i]; std::cout << "Product Info:" << std::endl; std::cout << "\tlocalizedTitle = " << [[myProduct localizedTitle] UTF8String] << std::endl; std::cout << "\tlocalizedDescription = " << [[myProduct localizedDescription] UTF8String] << std::endl; std::cout << "\tproductIdentifier = " << [[myProduct productIdentifier] UTF8String] << std::endl; std::cout << "\tprice = " << [[myProduct price] doubleValue] << std::endl; std::cout << "\tpriceLocale = " << [myProduct priceLocale] << std::endl; } [request autorelease]; } All my product IDs show up in the invalid printouts and none of them show up in the "Product Info:" printouts. Any suggestions would be greatly appreciated... P.S. Yes, this is built as Objective-c/c++.

    Read the article

  • comparison between string literal

    - by wiso
    This very simple code: #include <iostream> using namespace std; void exec(char* option) { cout << "option is " << option << endl; if (option == "foo") cout << "option foo"; else if (option == "bar") cout << "opzion bar"; else cout << "???"; cout << endl; } int main() { char opt[] = "foo"; exec(opt); return 0; } generate two warning: comparison with string literal results in unspecified behaviour. Can you explain why exactly this code doesn't work, but if I change char opt[] to char *opt it works, but generates the warning? Is it related to the \0 termination? What is the difference between the two declaration of opt? What if I use const qualifier? The solution is to use std::string?

    Read the article

  • Knight movement.... " how to output all possible moves. "

    - by josh kant
    hi tried the following code and is still not working. it is having problem on backtracking. it just fills the squares of a board with numbers but not in expected order. The code is as follows : include include using namespace std; int i=0; int permuteno = 0; bool move(int *p[], int *used[] ,int x, int y,int n, int count); bool knights (int *p[], int *used[],int x,int y,int n, int count); void output(int *p[],int n); int main(char argc, char *argv[]) { int count = 1; int n; //for size of board int x,y; // starting pos int **p; // to hold no. of combinations int **used; // to keep track of used squares on the board if ( argc != 5) { cout << "Very few arguments. Please try again."; cout << endl; return 0; } n = atoi(argv[2]); if( argv[1] <= 0 ) { cout << " Invalid board size. "; return 0; } x = atoi(argv[4]); y = atoi(argv[4]); cout << "board size: " << n << ", "<< n << endl; cout << "starting pos: " << x << ", " << y << endl; //dynamic allocation of arrays to hold permutation p = new int *[n]; for (int i = 0; i < n; i++) p[i] = new int [n]; //dynamic allocation of used arrays used = new int*[n]; for (int i = 0; i < n; i++) used[i] = new int [n]; //initializing board int i, j; for (i=0; i output(p,n); if (knights(p,used,x, y, n, count)) { cout << "solution found: " << endl < int i, j; for (i=0; i else { cout << "Solution not found" << endl; output (p, n); } knights (p,used, x, y, n, 1); //knights (p,used,x, y, n, count); cout << "no. perm " << permuteno << endl; return 0; } void output(int *p[],int n) { int i = 0,j; while ( i !=n) { for ( j=0; j bool move(int *p[], int *used[] ,int x, int y,int n,int count) { if (x < 0 || x = n) { return false; } if ( y < 0 || y = n) { return false; } if( used[x][y] != 0) { return false; } if( p[x][y] != 0) { return false; } count++; return true; } bool knights (int *p[], int *used[], int x,int y,int n ,int count) { //used[x][y] = 1; if (!move(p,used,x,y,n, count)) { return false; } if (move(p,used,x,y,n, count)) { i++; } p[x][y] = count; used[x][y] = 1; cout << "knight moved " << x << ", " << y << " " << count << endl; if(n*n == count) { return true; } //move 1 if (!knights (p,used, x-1, y-2, n, count+1)) { used[x][y] = 0; //p[x][y] = 0; } //move 2 if (!knights (p,used, x+1, y-2, n, count+1)) { used[x][y] = 0; //p[x][y] = 0; } //move 3 if (!knights (p,used, x+2, y-1, n, count+1)) { used[x][y] = 0; //p[x][y] = 0; } //move 4 if (!knights (p,used, x+2, y+1, n, count+1)) { used[x][y] = 0; //p[x][y] = 0; } //move 5 if (!knights (p,used, x+1, y+2, n, count+1)) { used[x][y] = 0; //p[x][y] = 0; } //move 6 if (!knights (p,used, x-1, y+2, n, count+1)) { used[x][y] = 0; //p[x][y] = 0; } //move 7 if (!knights (p,used, x-2, y+1, n, count+1)) { used[x][y] = 0; //p[x][y] = 0; } //move 8 if (!knights (p,used, x-2, y-1, n, count+1)) { used[x][y] = 0; //p[x][y] = 0; } permuteno++; //return true; //}while ( x*y != n*n ); return false; } I has to output all the possible combinations of the knight in a nXn board.. any help would be appreciated...

    Read the article

  • how to send classes defined in .proto (protocol-buffers) over a socket

    - by make
    Hi, I am trying to send a proto over a socket, but i am getting segmentation error. Could someone please help and tell me what is wrong with this example? file.proto message data{ required string x1 = 1; required uint32 x2 = 2; required float x3 = 3; } client.cpp ... // class defined in proto data data_snd; data data_rec; char *y1 = "operation1"; uint32_t y2 = 123 ; float y3 = 3.14; // assigning data to send() data_snd.set_x1(y1); data_snd.set_x2(y2); data_snd.set_x3(y3); //sending data to the server if (send(socket, &data_snd, sizeof(data_snd), 0) < 0) { cerr << "send() failed" ; exit(1); } //receiving data from the client if (recv(socket, &data_rec, sizeof(data_rec), 0) < 0) { cerr << "recv() failed"; exit(1); } //printing received data cout << data_rec.x1() << "\n"; cout << data_rec.x2() << "\n"; cout << data_rec.x3() << "\n"; ... server.cpp ... //receiving data from the client if (recv(socket, &data_rec, sizeof(data_rec), 0) < 0) { cerr << "recv() failed"; exit(1); } //printing received data cout << data_rec.x1() << "\n"; cout << data_rec.x2() << "\n"; cout << data_rec.x3() << "\n"; // assigning data to send() data_snd.set_x1(data_rec.x1()); data_snd.set_x2(data_rec.x2()); data_snd.set_x3(data_rec.x3()); //sending data to the server if (send(socket, &data_snd, sizeof(data_snd), 0) < 0) { cerr << "send() failed" ; exit(1); } ... Thanks for help and replies-

    Read the article

  • C++ floating point precision

    - by Davinel
    double a = 0.3; std::cout.precision(20); std::cout << a << std::endl; result: 0.2999999999999999889 double a, b; a = 0.3; b = 0; for (char i = 1; i <= 50; i++) { b = b + a; }; std::cout.precision(20); std::cout << b << std::endl; result: 15.000000000000014211 So.. 'a' is smaller than it should be. But if we take 'a' 50 times - result will be bigger than it should be. Why is this? And how to get correct result in this case?

    Read the article

  • Finding all the shortest paths between two nodes in unweighted directed graphs using BFS algorithm

    - by andra-isan
    Hi All, I am working on a problem that I need to find all the shortest path between two nodes in a given directed unweighted graph. I have used BFS algorithm to do the job, but unfortunately I can only print one shortest path not all of them, for example if they are 4 paths having lenght 3, my algorithm only prints the first one but I would like it to print all the four shortest paths. I was wondering in the following code, how should I change it so that all the shortest paths between two nodes could be printed out? class graphNode{ public: int id; string name; bool status; double weight;}; map<int, map<int,graphNode>* > graph; int Graph::BFS(graphNode &v, graphNode &w){ queue <int> q; map <int, int> map1; // this is to check if the node has been visited or not. std::string str= ""; map<int,int> inQ; // just to check that we do not insert the same iterm twice in the queue map <int, map<int, graphNode>* >::iterator pos; pos = graph.find(v.id); if(pos == graph.end()) { cout << v.id << " does not exists in the graph " <<endl; return 1; } int parents[graph.size()+1]; // this vector keeps track of the parents for the node parents[v.id] = -1; // there is a direct path between these two words, simply print that path as the shortest path if (findDirectEdge(v.id,w.id) == 1 ){ cout << " Shortest Path: " << v.id << " -> " << w.id << endl; return 1; } //if else{ int gn; map <int, map<int, graphNode>* >::iterator pos; q.push(v.id); inQ.insert(make_pair(v.id, v.id)); while (!q.empty()){ gn = q.front(); q.pop(); map<int, int>::iterator it; cout << " Popping: " << gn <<endl; map1.insert(make_pair(gn,gn)); //backtracing to print all the nodes if gn is the same as our target node such as w.id if (gn == w.id){ int current = w.id; cout << current << " - > "; while (current!=v.id){ current = parents[current]; cout << current << " -> "; } cout <<endl; } if ((pos = graph.find(gn)) == graph.end()) { cout << " pos is empty " <<endl; continue; } map<int, graphNode>* pn = pos->second; map<int, graphNode>::iterator p = pn->begin(); while(p != pn->end()) { map<int, int>::iterator it; //map1 keeps track of the visited nodes it = map1.find(p->first); graphNode gn1= p->second; if (it== map1.end()) { map<int, int>::iterator it1; //if the node already exits in the inQ, we do not insert it twice it1 = inQ.find(p->first); if (it1== inQ.end()){ parents[p->first] = gn; cout << " inserting " << p->first << " into the queue " <<endl; q.push(p->first); // add it to the queue } //if } //if p++; } //while } //while } I do appreciate all your great help Thanks, Andra

    Read the article

  • multi_index composite_key replace with iterator

    - by Rohit
    Is there anyway to loop through an index in a boost::multi_index and perform a replace? #include <iostream> #include <string> #include <boost/multi_index_container.hpp> #include <boost/multi_index/composite_key.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/ordered_index.hpp> using namespace boost::multi_index; using namespace std; struct name_record { public: name_record(string given_name_,string family_name_,string other_name_) { given_name=given_name_; family_name=family_name_; other_name=other_name_; } string given_name; string family_name; string other_name; string get_name() const { return given_name + " " + family_name + " " + other_name; } void setnew(string chg) { given_name = given_name + chg; family_name = family_name + chg; } }; struct NameIndex{}; typedef multi_index_container< name_record, indexed_by< ordered_non_unique< tag<NameIndex>, composite_key < name_record, BOOST_MULTI_INDEX_MEMBER(name_record,string, name_record::given_name), BOOST_MULTI_INDEX_MEMBER(name_record,string, name_record::family_name) > > > > name_record_set; typedef boost::multi_index::index<name_record_set,NameIndex>::type::iterator IteratorType; typedef boost::multi_index::index<name_record_set,NameIndex>::type NameIndexType; void printContainer(name_record_set & ns) { cout << endl << "PrintContainer" << endl << "-------------" << endl; IteratorType it1 = ns.begin(); IteratorType it2 = ns.end (); while (it1 != it2) { cout<<it1->get_name()<<endl; it1++; } cout << "--------------" << endl << endl; } void modifyContainer(name_record_set & ns) { cout << endl << "ModifyContainer" << endl << "-------------" << endl; IteratorType it3; IteratorType it4; NameIndexType & idx1 = ns.get<NameIndex>(); IteratorType it1 = idx1.begin(); IteratorType it2 = idx1.end(); while (it1 != it2) { cout<<it1->get_name()<<endl; name_record nr = *it1; nr.setnew("_CHG"); bool res = idx1.replace(it1,nr); cout << "result is: " << res << endl; it1++; } cout << "--------------" << endl << endl; } int main() { name_record_set ns; ns.insert( name_record("Joe","Smith","ENTRY1") ); ns.insert( name_record("Robert","Brown","ENTRY2") ); ns.insert( name_record("Robert","Nightingale","ENTRY3") ); ns.insert( name_record("Marc","Tuxedo","ENTRY4") ); printContainer (ns); modifyContainer (ns); printContainer (ns); return 0; } PrintContainer ------------- Joe Smith ENTRY1 Marc Tuxedo ENTRY4 Robert Brown ENTRY2 Robert Nightingale ENTRY3 -------------- ModifyContainer ------------- Joe Smith ENTRY1 result is: 1 Marc Tuxedo ENTRY4 result is: 1 Robert Brown ENTRY2 result is: 1 -------------- PrintContainer ------------- Joe_CHG Smith_CHG ENTRY1 Marc_CHG Tuxedo_CHG ENTRY4 Robert Nightingale ENTRY3 Robert_CHG Brown_CHG ENTRY2 --------------

    Read the article

  • Why isnt the copy constructor of member class called?

    - by sandeep
    class member { public: member() { cout<<"Calling member constr"<<'\n'; } member(const member&) { cout<<"Calling member copy constr"<<'\n'; } }; class fred { public: fred() { cout<<"calling fred constr"<<'\n'; } fred(const fred &) { cout<<"Calling fred copy constr"<<'\n'; } protected: member member_; }; int main() { fred a; fred b=a; } Output: Calling member constr calling fred constr **Calling member constr** Calling fred copy constr

    Read the article

  • C++ CIN cin skips randomly

    - by user69514
    I have this program, but cin in randomly skips.. I mean sometimes it does, and sometimes it doesn't. Any ideas how to fix this? int main(){ /** get course name, number of students, and assignment name **/ string course_name; int numb_students; string assignment_name; Assignment* assignment; cout << "Enter the name of the course" << endl; cin >> course_name; cout << "Enter the number of students" << endl; cin >> numb_students; cout << "Enter the name of the assignment" << endl; cin >> assignment_name; assignment = new Assignment(assignment_name); /** iterate asking for student name and score **/ int i = 0; string student_name; double student_score = 0.0; while( i < numb_students ){ cout << "Enter the name for student #" << i << endl; cin >> student_name; cout << "Enter the score for student #" << i << endl; cin >> student_score; assignment->addScore( Student( student_name, student_score )); i++; } }

    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

  • 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

  • Maddening Linked List problem

    - by Mike
    This has been plaguing me for weeks. It's something really simple, I know it. Every time I print a singly linked list, it prints an address at the end of the list. #include <iostream> using namespace std; struct node { int info; node *link; }; node *before(node *head); node *after(node *head); void middle(node *head, node *ptr); void reversep(node *head, node *ptr); node *head, *ptr, *newnode; int main() { head = NULL; ptr = NULL; newnode = new node; head = newnode; for(int c1=1;c1<11;c1++) { newnode->info = c1; ptr = newnode; newnode = new node; ptr->link = newnode; ptr = ptr->link; } ptr->link=NULL; head = before(head); head = after(head); middle(head, ptr); //reversep(head, ptr); ptr = head; cout<<ptr->info<<endl; while(ptr->link!=NULL) { ptr=ptr->link; cout<<ptr->info<<endl; } system("Pause"); return 0; } node *before(node *head) { node *befnode; befnode = new node; cout<<"What should go before the list?"<<endl; cin>>befnode->info; befnode->link = head; head = befnode; return head; } node *after(node *head) { node *afnode, *ptr2; afnode = new node; ptr2 = head; cout<<"What should go after the list?"<<endl; cin>>afnode->info; ptr2 = afnode; afnode->link=NULL; ptr2 = head; return ptr2; } void middle(node *head, node *ptr) { int c1 = 0, c2 = 0; node *temp, *midnode; ptr = head; while(ptr->link->link!=NULL) { ptr=ptr->link; c1++; } c1/=2; c1-=1; ptr = head; while(c2<c1) { ptr=ptr->link; c2++; } midnode = new node; cout<<"What should go in the middle of the list?"<<endl; cin>>midnode->info; cout<<endl; temp=ptr->link; ptr->link=midnode; midnode->link=temp; } void reversep(node *head, node *ptr) { node *last, *ptr2; ptr=head; ptr2=head; while(ptr->link!=NULL) ptr = ptr->link; last = ptr; cout<<last->info; while(ptr!=head) { while(ptr2->link!=ptr) ptr2=ptr2->link; ptr = ptr2; cout<<ptr->info; } } I'll admit that this is class work, but even the professor can't figure it out, and says that its probably something insignificant that we're overlooking, but I can't put my mind to rest until I find out what it is.

    Read the article

  • function pointer error

    - by Codeguru
    Can anybody help me with this simple code?? include using namespace std; void testFunction(){ cout<<"This is the test function 0"< void testFunction1(){ cout<<"This is the test function 1"< void testFunction2(){ cout<<"This is the test function 2"< int main(){ //fp=testFunction; (*fp[testFunction1])(); //cout<<"Addrees of the function pointer is:"<<*fp; } Iam getting the following error: error: invalid types `void (*[3])()[void ()()]' for array subscript|

    Read the article

  • error by creating process

    - by Tyzak
    hello i want to get startet with programming with WIN32, therefore i wrote a programm that creates a process but in the line of code where i create the process the programm gets an error an dosn't work (abend). i don't know if the code in programm 1 is wrong or the code in the second programm that should be created by the first. ( I don't know if the code in the first programm after "createprocess" is right because i didn't get further with debugging, because in this line i get the error.(i tested it without the cout,waitforobject and close handle but i didn't work either )). First Programm: #include <iostream> #include <windows.h> #include <string> using namespace std; void main() { bool ret; bool retwait; STARTUPINFO startupinfo; GetStartupInfo (&startupinfo); PROCESS_INFORMATION pro2info; ret = CreateProcess(NULL, L"D:\\betriebssystemePRA1PRO2.exe", NULL, NULL, false, CREATE_NEW_CONSOLE, NULL, NULL, &startupinfo, &pro2info); cout<<"hProcess: "<<pro2info.hProcess<<endl; cout<<"dwProcessId: "<<pro2info.dwProcessId <<endl; retwait= WaitForSingleObject (pro2info.hProcess, 100); retwait= WaitForSingleObject (pro2info.hProcess, 100); CloseHandle (pro2info.hProcess);//prozesshandle schließen retwait= WaitForSingleObject (pro2info.hProcess, 100); ExitProcess(0); } Seconde Programm: #include <iostream> #include <windows.h> #include <string> using namespace std; void main() { int b; b=GetCurrentProcessId(); cout<<b<<endl; cout<<"Druecken Sie Enter zum Beenden"<<endl; cin.get(); //warten bis Benutzer bestätigt Sleep (700); ExitProcess(0); cout<<"test"; } Thanks in advance

    Read the article

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