mrnutty 761 Senior Poster

C++ doesn't have an interface to allow you to create any GUI code, but you can use external libraries to draw the GUI stuff and control it with C++.

For example here is a gui application in C++ using the QT library:

#include <qapplication.h>
#include <qpushbutton.h>


int main( int argc, char **argv )
{
    QApplication a( argc, argv ); //create a window object

    //create a button object with the text 'hello world'        
    QPushButton hello( "Hello world!", 0 ); 
    //set the size of the button
    hello.resize( 100, 30 );
    //add it to the window
    a.setMainWidget( &hello );
    //enable our button to be shown, by default it is hidden      
    hello.show();
    //show our whole window
    return a.exec();
}

There are many tutorials out there for this, I just stole the above from here: http://web.njit.edu/all_topics/Prog_Lang_Docs/html/qt/tutorial1-01.html ,

But judging from your post, I do not suspect that you have grasped most of the concepts in C++, so I would suggest to start doing more projects and not worry about gui stuff until you have a solid grasp of C++. How much of its concepts do you know, for example arrays/if-else/classes/structs/templates?

Ancient Dragon commented: good advice +14
mrnutty 761 Senior Poster

Maybe this startup hint would help you

#include <iostream>
using namespace std;

void getMonthsData(int data[], const int SIZE){
  //print message
  //for i = 0 to size 
    //ask for data[i]

}
void getYearData(int data[], const int SIZE){
 //print message
 //for i = 0 to size
   //ask for data[i]
}

void getAverate(int data[],const int size){
 //your get_average logic here
}

int main(){
 int data[12] = {0}; //zero initialize everything
 int MAX_SIZE = 12;

 int choice = -1;
 cin >> choice; //get user input

 switch(choice){
  case 1: MAX_SIZE = 12; getMonthsData(choice,MAX_SIZE); break;
  case 2: MAX_SIZE = 10; getYearData(choice,MAX_SIZE); break;
 }
 cout << "Average= " << getAverage(choice,MAX_SIZE) << endl;
 return 0;
}
mrnutty 761 Senior Poster

If you are going to go the iterator route, then you might as well make it stl compatiable and inherit from `std::iterator'.

Another option is to simply have a filter function like so:

template<typename Container, typename FilterCondition>
std::vector<typename Container::value_type> filter(const Container& cont, const FilterCondition& cond){
 std::vector<typename Container::value_type> filteredList;
 for(int i = 0; i < cont.size(); ++i){
    if(cond( cont[i] )) filteredList.push_back( cont[i] );
 }
 return filteredList;
}

bool isDead(const Actor& actor){ return actor.isDead(); }
bool isChildActor(const Actor& actor){ return actor.age() < 18;}
bool isGirlActor(const Actor& actor){ return actor.type == Actor::GIRL_ACTOR: }
int main(){
  ActorList actors = getActors();
  ActorList childActors = filter( actors , isChildActor );
  ActorList childActorWhoAreGirls = filter( childActors, isGirlActor );
  //..and so on

Warning, syntax is probably wrong somewhere, but the general advice should help.

mrnutty 761 Senior Poster

In C++ 1/2 = 0 because of inteeger division. Thus you want something like so:

float divide(float x, float y){ return x/y;}
int main(){
 float x = 0, y = 1;
 cin >> x >> y;
 cout << divide(x,y) << endl;
}
mrnutty 761 Senior Poster

It should be something like so, in psuedo code:

bool isFull(board){
  bool isFull = true;
  for i = 0 to board.length   # 0 <= i <= 8
    if board[i] != 'x' && board[i] != 'o'
       isFull = false;
       break;

  return isFull;
}
mrnutty 761 Senior Poster
  • Check if the board is full, meaning that all cells are occupied and not empty
  • Then make sure there aren't any winning patterns for 'x' -- use your checkAll('x')
  • Then make sure there aren't any winning patterns for 'o' -- use your checkAll('o')
  • If all the above passed then it is a tie
mrnutty 761 Senior Poster

Your asking for private code. I told you what I was doing.

Welp for one calm that attitude down. Second good luck with your problem then.

mrnutty 761 Senior Poster

Rather than trying to explain, I'll link you to a article that talks about namespace. In general for simple question you should try to be more independent. Take care.

mrnutty 761 Senior Poster

Somthing like this perhaps

template<typename FirstContainer, typename SecondContainer, typename BinaryOp>
void iterateTwoContainer(const FirstContainer& firstList,
                         const SecondContainer& secondList,
                         const BinaryOp op2){
 for(int i = 0; i < firstList.size(); ++i){
   for(int j = 0; j < secondList.size(); ++j){
     op2(firstList[i],secondList[j]);
   }
 }
}

void handleItemAndToys(const Item1& item, const Toy& toy){/*...*/}
void handleItemAndApples(const Item2& item,const Apple& apple){ /*...*/}
int main(){

   iterateTwoContainers(listOfItem1,listOfToys,handleItemAndToys);
   iterateTwoContainers(listOfItem2,listOfAppels,handleItemAndApples);
}
myk45 commented: thanks! +5
mrnutty 761 Senior Poster

You probably wany New(Shoe,num);

mrnutty 761 Senior Poster

leaf = leaf->left; //move leaf 1 time to right

That comment conflicts with that is written.

leaf->key_value = temp->key_value; //assigning temp's key to leaf

That's not really needed since leaf is going to be deleted right.

Also I'm not sure why you are treating left-child different than right child when deleting using that algorithm. All you are doing is swapping a leaf node with the node to be deleted and deleting the stale leaf node. I don't see how this algorithm has any relation to a leaf having two children as your function deleteWithTwoChild suggests. Just being nitpicky there. If this is fro homework, then you probably want to follow the proper guidlines.

Anyways, can you print out the tree after each deletion? Also what happens if father is null? Have sanity check to see if father or temp is null. If possible post full code in pastebin.com because, the problem might be elsewhere. Can you post your deleteWithNoChild function? And also the destructor for this class.

deepecstasy commented: Comment is correct, yes leaf->key_value modification doesn't make a difference but I just wrote it to be clear, & I have pasted required functions, +0
mrnutty 761 Senior Poster

I know the question was who, but lets cover more ground my casting it to what. What makes me happy are the things I love to do and enjoy. Some of which are

  • Spending time with family
  • Spending time with my brother, more specifically
  • Playing basketball
  • Programming
  • Making people smile
  • Helping people to make their day better
  • Simply appreciating life, and so much more
mrnutty 761 Senior Poster

Yes in C++ you can return a pointer by reference, doing so will allow you to change the pointing address of the pointer and have it affect out of scope. For example

void reallocateRef(Node*& node, int newValue){
    node = new Node(newValue);
}
void reallocateNoRef(Node* node, int newValue){
    node = new Node(newValue);
}
//...
Node * n1 = new Node(-1);
Node * n2 = new Node(1);
reallocateRef(n1, 0); //   n1.value = 0 instead of -1
reallocateNoRef(n2,0); // n2.value is still 1 instead of 0

As for what it is good for, it depends on context, somtimes it plays a good role for helper function and other times you just might need it. Usually you just pass pointer by value, but if you need to change what it is pointing to then it is necessary to pass by reference. There could be similar reasoning for returning by value versus ref for pointers.

mrnutty 761 Senior Poster

Initialize you letter grades.

 char A('A'), B('B'), C('C'), D('D'), E('E'), F('F');
mrnutty 761 Senior Poster

Taking a quick look,

" index=sub.find_first_not_of("aeuio");
    cout << "first consonant:"<< sub[index]<<endl;
"

what happens when that find_first_not_of fails?

mrnutty 761 Senior Poster

How about adding some graphical feature to show the statistics on the number of successes the job finding site has acomplished?

mrnutty 761 Senior Poster

Go for sfml, but there might be more documentation on sdl. Check out gamedev, they are generally good with helping with graphics. Or you can post here and we'll help as well. Just get some simple screen gonig on sfml then move on further from there.

mrnutty 761 Senior Poster

You listed the answer, 1 = 5 therefore 5 = 1.

Sometimes simplicity is overlooked.

mrnutty 761 Senior Poster

First you want to look at batch programming, at least I think that's a good starting point to showoff to your friends. Second, grow some balls. Who cares what they think? Why do you need to impress them. They are not programmers and probably never will be. They do not have any knowledge in our field. They just go by whatever is shown in the movies. Third, get a internship, get a job, contribute to open source, create an open source project, make your own programming projects. Do stuff that you can put on your resume. That's how you will impress recruiters.

mrnutty 761 Senior Poster

Another option is to make a File struct.

struct FileInfo{
    std::string name;
    //possibly other things
    explicit FileInfo(const std::string& name = ""): name(name){}
}

class Lexical{
     ReturnType read(const std::string& sentence);
     ReturnType read(const FileInfo& fileInfo);
}

but I suggest to go the istream route as suggested in previous post.

mrnutty 761 Senior Poster

And I have partly to thank you guys. I joined DW a while back only occasionly used it. Then stoped. Then started using it more and more. Over the years it has been great. Everything has been great. Everyone has been great. I wish it was possible that we could all go out and have a drink or something. I feel like I owe you guys one. Anyways, I don't want to get too mushy gushy. You guys have been a good part of my life. I remember constantly logging on here to either ask questions or answer them. While I was obsessed with programming for a few years a while back, you guys gave me the resource and fire to fuel that obsesison. Now it has died down a bit. You guys might not know it but you guys helped me through life a lot. From programming to relationship issues to religion. Extra thanks to imthewee, man you are one awsome person. I don't really know the point of this article, but I just want to show my appreciation to you guys. Man I'm such a bitch lol. Time flies by so quick. Hope everyone has been well up to this point. I like the new DW look although some new features annoy me. Take care ladies/gents.

yours truly,

D.Chhetri

mrnutty 761 Senior Poster

You're looking for conversion operator. Something like

class Point{
  private:
    int x,y;
  public:
    operatir POINT()const{
       return POINT(x,y);
    }
};
triumphost commented: Perfect! I never ever saw that before. Thank you. +5
mrnutty 761 Senior Poster

I think the syntax is

int rowSize = 5;
int colSize = 5;
float **matrix = new float*[rowSize];
for(int i = 0; i < rowSize; ++i){
  matrix[i] = new float[colSize];
}

//do stuff with matrix[i][j]

//delete
for(int i = 0; i < rowSize; ++i){
   delete [] matrix[i];
}
delete [] matrix;

Of course you can avoid all of this by using std::vector.

  int rowSize = 5;
  int colSize = 5;
  std::vector< std::vector<float> > matrix( rowSize, std::vector<float>(colSize) );

  //use matrix[i][j]

  //no need to worry about deleting matrix
mrnutty 761 Senior Poster

"First part is simple, my name is mike. The second part is an enigma for you guys. 2000 taken to the power 17 is about the total mass of the observable universe measured in grams. No, actually 2000 bitshifted 17 times writes FA00000 in hex which is cool. I'm kidding, seriously, 2000 and 17 is the longitude and lattitude of this private island that I own. Muhuahaha, you'll never figure out what it means!

Also python (the animal) is spelled pyton in Finnish.
Yeah, when a finnish colleague of mine proposed to use "pyton" for a project we had, said in the finnish pronounciation, it took me a while to realize he was talking about Python. Minä rakastan Suomi, mutta se on mahdotonta oppia suomea!"

Hmmm, hurricane michael ? Occured in the year 2000 on the 17th of october as a tropical storm?

mike_2000_17 commented: That's an awesome coincidence! +0
mrnutty 761 Senior Poster

I haven't worked with mandelbrot set but try using this :

//zn is your last complex number used and n is the iteration count
flota smoothcolor = n + 1 - Math.log(Math.log(zn.abs()))/Math.log(2)
Color col = Color.HSBtoRGB(0.95f + 10 * smoothcolor ,0.6f,1.0f);
mrnutty 761 Senior Poster
mrnutty 761 Senior Poster

>>M- happens to be a unknown function of N

That means, M = f(N), and you can't assume anything about f(N), so the runtime would be O(N * f(N)).
That could be linear, polynomial, quadratice, factorial, or whatever; all depending on f(N)

grh1107 commented: thanks! very helpful +1
mrnutty 761 Senior Poster
INPUT-BUFFER: 973 456.2 77F NEWLINE 973 456.2 77F

1)	cin>> m;  //m = 973 
INPUT-BUFFER: 456.2 77F NEWLINE 973 456.2 77F

2)	cin.clear (); //clears the state bits
INPUT-BUFFER: 456.2 77F NEWLINE 973 456.2 77F

3)	cin.ignore (200, '\n');  //ignores 200 characters or until a new line is reached
INPUT-BUFFER: 973 456.2 77F

4)	cin>> letter>> n>> n;   //letter = '9' , n = 73 then n = 456

INPUT-BUFFER: [ is in a failed state I think not sure, sets the state bits ]

5) cout<< letter<< m<< n<< endl; //pass out 9973456
mrnutty 761 Senior Poster

Pass them by reference. Its better than polluting globals.

mrnutty 761 Senior Poster

Also for B), O(n+m) \in O(n) so you can just say O(n)

mrnutty 761 Senior Poster

Yes, but if you want to do it that way, you need to do manual allocation.

void foo(string** strs, int width, int height){
 //...
}
int main(){
 int width = 0, height = 0;
 cin >> height >> width;
 string **strs = new string*[height];
 for(int i = 0; i < height; ++i){
  strs[i] = new string[width];
 }
 
 foo(strs, width, height);
}

You might want to skip doing manual memory management and possible use std::vectors

typedef std::vector<string> StringArray;

void foo(std::vector<StringArray>& arrayList){
 //...
}

int main(){
  int height = 0, width = 0;
  cin >> height >> width;
  std::vector<StringArray> myList(height , StringArray(width) );
  
   foo(myList);
}
mrnutty 761 Senior Poster

List of free programming books. Enjoy and happy new year!

mrnutty 761 Senior Poster
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
using namespace std;

int main(){
 cout << 
"           ___\n         /`   `'.\n        /   _..---;\n        |  /__..._/  .--.-.\n        |.'  e e | ___\\_|/____\n       (_)'--.o.--|    | |    |\n      .-( `-' = `-|____| |____|\n     /  (         |____   ____|\n     |   (        |_   | |  __|\n     |    '-.--';/'/__ | | (  `|\n     |      '.   \\    )"";--`\\ /\n     \\        ;   |--'    `;.-'\n     |`-.__ ..-'--'`;..--" << endl;

 return 0;
}
Clinton Portis commented: "E" for effort (: +10
jonsca commented: Nice one! +14
mike_2000_17 commented: Nice +14
mrnutty 761 Senior Poster

You can use a try/catch block in the initializer list. Check out this site. Here is the live code as an example.

#include <iostream>

struct BadObject{
 BadObject() {}
 BadObject(int i){ throw("Why you no work 0_o?"); }
};

struct GoodObject
{
 BadObject b;
 GoodObject(int i)
   try : b( BadObject(i) )
   {}
   catch(const char *p)
   { cout << "Runtime Error: " << p << endl; }
};

int main(){
 GoodObject obj(0);

 return 0;
}
mrnutty 761 Senior Poster

"Give a man a fish, you feed him for a day. Teach a man how to fish and you feed him for lifetime"

My son, I will teach you how to fish

myk45 commented: haha, nice one. +6
mrnutty 761 Senior Poster

Dont read it line by line. Instead, read it word by word. The check if each word is a valid real number. Example:

int main(){
 ifstream fileIn("input.txt");
 string word;
 unsigned int count = 0;
 while( fileIn >> word )
 {
    if( isRealNumber( word ) ){  //you need to implement isRealNumber
        ++count;
    }
 }
}

Note in the above I assume each words are separated by spaces

mrnutty 761 Senior Poster

Another option is to supply your comparison method to std::sort:

int getDigitFromLine(const std::string& line){
  const string digits = "0123456789";
  size_t beg = line.find_first_of(digits);
  size_t end = line.find_first_of(digits);
  string digitString = line.substr(beg, end-beg + 1);
  return atoi( digitString.c_str() ); 
}
bool mycomp(const std::string& lhs, const std::string& rhs){
  int lhsNumber = getDigitFromLine(lhs);
  int rhsNumber = getDigitFromLine(rhs);
 return lhsNumber < rhsNumber;
}
int main(){
 //populate vector
 std::sort( vec.begin(), vec.end(), mycomp);
}
mrnutty 761 Senior Poster

>>Even though both variables have the value 30 in it, the if-condition gets satisfied and exception is thrown

The int gets promoted and you are now doing a floating comparison. When doing floating comparison, as of right now you can do a simple range comparison :

//checks if lhs is equal to rhs given an epsilon
//that is returns true if lhs \in (rhs-epsilon,rhs+epsilon)
bool isEqual(const double lhs, const double rhs, const double epsilon = 0.0001){
  return lhs > rhs - epsilon && lhs < rhs + epsilon ;
}
mrnutty 761 Senior Poster

>> Should I include the whole path name or just the image name?

If the file is in the same directory as your source file, then you can just use the filename, else you can either use relative path or full path. However it needs to be a valid path.


>>file = fopen(filename, "C:\\Users\\annette\\My Pictures\\face.png");

You want, file = fopen(filename,"r"); and the call can be GLuint texture = LoadGLTexture("C:\\Users\\annette\\My Pictures\\face.png", 396, 734);

BoBok2002 commented: This post was helpful and well explained. I understood it clearly +2
mrnutty 761 Senior Poster

I'm graduating this december and I got a job offer!!! Will be working for FactSet. I can't believe it. This is so crazy. Thanks everyone for helping me when in need. I'm just so happy :)

regards firstPerson

Ancient Dragon commented: Good work :) +0
mrnutty 761 Senior Poster

Sure. First realize that Menu's can be recursive, that is you can have menues inside menus. For example, you can have a top level menu called, Clothes which contains sub-menus like sports clothes or winter clothes. Noticing this recursive structure, might hint that a tree implementation might be a natural choice. Noting the above, here is some idea to go by.

struct Menu{
 std::string name; //could be menu name or a item name
 std::vector<Menu> subMenus;
Menu(const std::string& name, const std::vector<Menu> subMenus): name(name), subMenus(subMenus){}
 void add(const Menu& m){ subMenus.push_back(m); }
};

class SportsClothingMenu{
private:
 Menu sportsClothingMenu;
public:
 SportsClothingMenu(){}
private:
 void _populate(){
        Menu soccerClothesMenu("soccer");
        //...add soccor clothes to soccerClothesMenu
        sportsClothingMenu.add( soccerClothesMenu );
  }
}

Note that we know a menu is a leaf if it has no children, so in the above case if subMenu.empty() is true. You should be able to take it from there. There is no real need to use pointers here. Using std::vector will suffice.

Interista commented: Ur a Champion +0
mrnutty 761 Senior Poster

Your code is hard to read but your problem is in line 15, your using the array and it hasn't event been initialized it. Usually when you use an array, you you use hardcoded index when you want to access all values. What you are looking for is something like so:

int main(){
 const int size = 4;
 int values[size] = {0}; //set all values to 0;
 for(int i = 0; i < size; ++i){
     int input = 0;
     cin >> input; //get user input
     //check if it matches any previously inputted values
      bool isUnique = true;
     for(int j = i - 1; j >= 0; --j){
           if(input == values[j]){ //if current value is equal to the newly inputted value
               isUnique = false; //set state to false
               break;     //exit out of this for loop;
           }
     }
    if(isUnique){ //if is unique, save it
         values[i] = input; 
     } else{
            cout << "\nError value is not unique\n";
            //reset counter
             --i;
     }
 }
}
babyhuyx commented: Amazing, Very Helpful, totally opened my mind to new way of coding +1
mrnutty 761 Senior Poster

>>Weird and redundant, isn't it?

For now yes, but if you guys decide to not use "_T" then you can simply change the macro definition instead of changing the code a whole lot for accommodate the new type.

mrnutty 761 Senior Poster

An example:

#include <ctime>
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

int getRandom(){ return rand() % 500; } 

int main(){
 srand(time(0)); //seed random number function
 int size = 0;
 cout << "Enter size: ";
 cin >> size;
 
 std::vector<int> data(size,0); // contains size number of 0's
  
 std::generate(data.begin(), data.end(), getRandom ); //fill vector with random numbers from [0,500)
}
mrnutty 761 Senior Poster

If you have something like a factory pattern then you can enforce it, for example:

class CandyFactory{
 private:
  struct ChoclateBar(){ 
        int calories; 
        ChoclateBar(): calories(){}
   };
 public:
  shared_ptr<ChoclateBar> makeChoclateBar(){
       return shared_ptr( new ChoclateBar() )
  }
};

I don't know if thats what you were asking?

mrnutty 761 Senior Poster

>>getline(cin, first_sphere[3]);
You want: cin >> first_sphere[0] >> first_sphere[1] >> first_sphere[2] Also as suggested, move this code

float RadiusofTwoSpheres(float *sphere1, float *sphere2);
	{
		cout << "The Radius for Sphere's 1 and 2 is... " << endl;
		cout << endl;
		cout << "R = " << (float)sqrt(pow(sphere2[0] - sphere1[0], 2) + pow(sphere2[1] - sphere1[1], 2) + pow(sphere2[2] - sphere1[2], 2)) << endl;
	};

before int main(){}

Zvjezdan23 commented: Thank You so much for helping me. =) +0
mrnutty 761 Senior Poster

Idk if this works but maybe try out using this algebra:

1/9 = 0.1111....
9 * 1/9 = 9 * 0.1111
1 = 0.999....

See if you get similar result on a computer.

mrnutty 761 Senior Poster

If you are using std::stack, then there isn't any concept of iterators for std::stack, which makes sense.

As for your question, you can copy the stack content if needed. But it looks like you shouldn't be using stack in the first place?

mrnutty 761 Senior Poster

>> cin >> a >> b >> read_hw(cin, homework);

that essentially turns into cin >> cin which doesn't make sense. I agree, for your function, read_hw you should make it void. Enabling syntax such as read_hw(cin,homework) >> a >> b is obfuscated.

Just think read_hw as a regular function and call it as a regular function in its own statement. Don't try to use the returned value as there is no need. A better approach would be this :

#include <iostream>
#include <cstdlib>
#include <iostream>
#include <vector>

using namespace std;

istream& operator >>(istream& in, vector<double>& hw)
{
    if (in)
    {
        // get rid of previous contents
        hw.clear();
        // read homework grade
        double x;
        while (in >> x)
            hw.push_back(x);
        // clear the stream so that input will work for the next student
        in.clear();
    }
    return in;
}

int main()
{
    double a, b;
    vector<double> homework;
    cin >> a >> b >> homework;

    cin.get();
    return 0;
}
mrnutty 761 Senior Poster

Oh right, you need to seed first.

#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <vector> 
#include <string>
#include <ctime> 

using namespace std;

int main(int argc, char *argv[])
{
    srand( time(0) ); //seed

    cout<<"Current Car Pool Riders/Drivers\n";
    cout<<endl;
    cout<<"Monday - Nathan\n";
    cout<<"Tuesday - Jimmy\n";
    cout<<"Wednesday - Cochran\n";
    cout<<"Thursday - Harris\n";
    cout<<endl;
    vector< string > drivers;
    drivers.push_back("Jimmy");
    drivers.push_back("Nathan");
    drivers.push_back("Cochran");
    drivers.push_back("Harris");
 
    std::random_shuffle( drivers.begin(), drivers.end() );
 
    string pick = drivers[0];
    cout<<"The Person Driving this Friday is - " << pick << endl;
    cout<<endl;
 
    system("PAUSE");
    return EXIT_SUCCESS;
}
NetJunkie commented: Worked like a charm :) +3