• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

C++ Help?

Status
Not open for further replies.

usea

Member
For algorithms questions, I hate to say it, but read about about programming interview questions. It's the best bang for your buck in terms of actually being prepared for what they might ask.
Agreed.

Some of the types of questions asked at interviews are usually some kind of string manipulation, maybe a sort or search. Usually they're just trying to gauge your overall competency, not that you know some specific algorithm. Usually they'll give you pseudocode for the algorithm and ask you to implement it. But it helps to be familiar with them :)
 

BlueMagic

Member
So I have this CollisionEntity class which has many subclasses. In this class I have a method that detects collision for the entity. I also want it to contain a way to respond to those collisions, so I coded a method called onCollision() which is supposed to have as many implementations as subclasses of the CollisionEntity class and should be called when the collision is detected against another collision entity, in such a way that I have a onCollision(BasicEnemy* enemy), onCollision(Bullet* bullet), etc, called everytime a collision is detected against an object of that specific type.
However all these classes will be subclasses of the original class, and therefore the compiler never knows what onCollision implementation I'm referring to (since CollisionEntity checks for collisions against another CollisionEntity in a generic way, and therefore it will never cast the entity to whichever class it corresponds with).

I don't know if I expressed myself correctly but is there an easy way to do this?
 

Haly

One day I realized that sadness is just another word for not enough coffee.
You can have an enumeration in CollisionEntity, something like:

enum CollideTypes
{
BULLET,
ENEMY;
}


Then change the collision method to collideWith(CollisionEntity *target, int collisionType). In the method, you cast the pointer depending on which type was passed in, and then call onCollide(<casted pointer>).

Not a very elegant solution though.
 

maharg

idspispopd
So I have this CollisionEntity class which has many subclasses. In this class I have a method that detects collision for the entity. I also want it to contain a way to respond to those collisions, so I coded a method called onCollision() which is supposed to have as many implementations as subclasses of the CollisionEntity class and should be called when the collision is detected against another collision entity, in such a way that I have a onCollision(BasicEnemy* enemy), onCollision(Bullet* bullet), etc, called everytime a collision is detected against an object of that specific type.
However all these classes will be subclasses of the original class, and therefore the compiler never knows what onCollision implementation I'm referring to (since CollisionEntity checks for collisions against another CollisionEntity in a generic way, and therefore it will never cast the entity to whichever class it corresponds with).

I don't know if I expressed myself correctly but is there an easy way to do this?

This is what virtual methods are for. There's a performance impact, potentially, but it's probably not significantly worse than the performance impact of the switch approach Haly suggested.
 

Blizzard

Banned
So I have this CollisionEntity class which has many subclasses. In this class I have a method that detects collision for the entity. I also want it to contain a way to respond to those collisions, so I coded a method called onCollision() which is supposed to have as many implementations as subclasses of the CollisionEntity class and should be called when the collision is detected against another collision entity, in such a way that I have a onCollision(BasicEnemy* enemy), onCollision(Bullet* bullet), etc, called everytime a collision is detected against an object of that specific type.
However all these classes will be subclasses of the original class, and therefore the compiler never knows what onCollision implementation I'm referring to (since CollisionEntity checks for collisions against another CollisionEntity in a generic way, and therefore it will never cast the entity to whichever class it corresponds with).

I don't know if I expressed myself correctly but is there an easy way to do this?
If you have to pass a CollisionEntity* around and you need to access say, bullet-specific data in the CollisionEntity, then you will have to do (dynamic_cast) downcasts regardless. You could do a switch statement like Haly suggested, or you could name your methods different things like HitBullet, HitPlayer, etc.

I almost wonder if you have a design issue, however. If it is just a question of "what type is the entity I just hit", you can implement a GetEntityType method in your CollisionEntity, and have every subclass return something different. That way you don't need any casts and you can implement a generic onCollision method.

If you find yourself needing to know implementation details of the thing you just collided with, I suggest that might be a design issue that would be better served by calling a method on the entity you collided with...though even that may require a downcast if it's a very entity-type-specific method.

I don't know if any of that was very good advice. :X
 

TheBez

Member
When creating a function that accepts three integers what would I do to make it return those integers in numerical order? For example if the user inputted 3, 2, 1 i would want it to return 1, 2, 3.
 

Haly

One day I realized that sadness is just another word for not enough coffee.
1. Write a swap function that takes in two pointers to integers and swaps their values.
2. Implement Selection Sort.
 

TheBez

Member
1. Write a swap function that takes in two pointers to integers and swaps their values.
2. Implement Selection Sort.

Oh uhm haha, I guess I should mention it's my first semester so I have limited resources available to what I know and should therefore use. Hmm i guess Ill see if I cant figure this out myself :) Thank you for your help though!
 

Haly

One day I realized that sadness is just another word for not enough coffee.
Okay, my bad, I'll go into more detail.

You have 3 integers, x, y and z.

1. First, you need to figure out how to switch the values of x and y, or y and z, or x and z. You can find this online, or in a textbook or just by sketching it out on a piece of paper. It involves a variable we'll call temp, which is used to store values during the swap.

2. Then look at the wiki page I linked you to. The algorithm for selection sort is really simple and possibly the first one most people learn.

Visually it'll look like this. Let's say x = 10, y = 6, and z = 8, so your 3 integers look like:

[10][6][8]

First, compare x and y. If x is greater than y, swap them, if not, leave them alone. Since 10 is greater than 6, they should be swapped so now you're left with:

[6][10][8]

Next, compare x and z. If x is greater than z, swap them, if not, leave them alone. Since 6 is smaller than 8, there's no need to swap so you still have:

[6][10][8]

Finally, compare y and z. If y is greater than z, swap them, if not, leave them alone. Since 10 is greater than 8, they should be swapped so now you're left with:

6810

All that's left is to print out x, y and z to the console. Notice that in this case, step 2 didn't do anything. However, if the numbers were [10][8][6], step two would be necessary to turn [8][10][6] to [6][10][8].
 

TheBez

Member
You learned about classes/structs before vectors? That seems really strange to me.

Actually, let me redact that, was thinking of something else. I have something to turn in, its not pretty but it will get the job done and its only 10 points so its not make or break. Thank you guys so much for attempting to help :)
 

Haly

One day I realized that sadness is just another word for not enough coffee.
I don't think most intro classes start off with STL containers. They usually have you code all these various data structures first, then they tell you to throw them in the garbage because better programmers have figured all this stuff out and it's all built in for you.
 

Bruiserk

Member
I don't think most intro classes start off with STL containers. They usually have you code all these various data structures first, then they tell you to throw them in the garbage because better programmers have figured all this stuff out and it's all built in for you.

Haha yea, isn't that the truth. But I learned vectors in both my intro courses (Python and C++).
 

TheBez

Member
Ah. So, what is the function signature?

Heres what I came up with, like I said it is not elegant. Edit: Dont mock me :p

Code:
#include <iostream>
#include <cmath>
#include <cstdlib>

using namespace std;
int diff(int x, int y, int z);


int main()
{
int num1, num2, num3;
cout << "Enter some Integers and I will report them back in proper numerical order: " << endl;
cin >> num1>>num2>>num3;

int p = diff(num1,num2,num3);

cout << p << endl;

return 0;
}

int diff(int x, int y, int z)
{
if(x > y > z)
{
	return (x ,y ,z);
}
if(x > z > y)
{
	return (x, z, y);
}
if(z > x > y)
{
	return (z, x, y);
}
if (z > y > x)
{
	return (z, y, x);
}
if (y > x > z)
{
	return (y, x, z);
}
if (y > z > x)
{
	return (y, z, x);
}
}
 

Slavik81

Member
There's a few problems in that code. I'll update this post as I go through them.

1.
Code:
	return (x ,y ,z);
This is the same as:
Code:
	return z;

You're accidentally using the comma operator here. It does not do what you think it does. It evaluates all the statements you've separated by commas, but returns only the last one.

2.
Code:
if(x > y > z)
This also does not do what you think it does. x > y > z means (x > y) > z.
The result of x > y is a bool. So that means you're checking either
true > z or false > z

true will be counted as 1. false will be counted as zero.

Thus, your statement there is the same as:
Code:
if((x > y && 1 > z) || (x <= y && 0 > z))
{
   // true
}
else
{
   // false
}

3. diff is a really odd name for a function that sorts integers

4. there's no way that compiles with all of your return statements being in if blocks. (EDIT: It's sust a warning under vs2008) the compiler's almost certainly going to complain that it's not sure it will return from diff, even if you really did account for every possible outcome in those if statements. An if/if else/else chain might be better for your current approach.

5. diff should probably return more than just a single integer. perhaps a you could make a struct that has 3 integers in it? call them first, second and third, or something, and return it with those values filled in. cout won't know how to handle the entire structure at once, but you can just give it first, second and third one value at a time and it will output them fine.

EDIT: Good luck, and good night. I'm going to bed.
 

Slavik81

Member
Actually, I'm back to say one more thing. I know I posted a lot of problems, but don't feel bad about it. Those first two problems in particular I think are more the fault of the C++ language. The comma operator should never have existed and implicit conversions between bools and integers (and pointers) cause all kinds of confusion. There should also be a better way for checking ranges in C++.

C++ is a confusing language but you're off to a good start.
 

TheBez

Member
Actually, I'm back to say one more thing. I know I posted a lot of problems, but don't feel bad about it. Those first two problems in particular I think are more the fault of the C++ language. The comma operator should never have existed and implicit conversions between bools and integers (and pointers) cause all kinds of confusion. There should also be a better way for checking ranges in C++.

C++ is a confusing language but you're off to a good start.

I appreciate it, the constructive criticism will only help! Plus I knew my first thing back from break would probably be an abomination.
 

Slavik81

Member
Ok, seriously I'm really going to bed this time. Just one more thing again...

Do not ignore warnings unless you know exactly what they mean. #2 and #4 have warnings under visual studio 2008 and addressing them would have helped you to improve your code.
 

Kalnos

Banned
Curious, does the assignment actually say that you need to return a value? It would be just as easy to print the result inside of each if statement if you have no experience with any data structure (array, vector, etc).
 
Code:
int main ()
{
 int a = 0; //vote for Mr. A
 int b = 0; //vote for Ms. B
 int n = 0; //vote for nobody
 int i = 0; //counter
 int temp = 0; //tally

   for (i = 1; i <= 10; i++)
	{
	   printf("Please cast your vote: (1) for Mr. A or (2) for Ms. B\n");
	   scanf("%d", &temp);
	   if (temp = 1)
		{
		   a = a + 1;
		}
	   else if(temp = 2)
		{
		   b = b + 1;
		}
	   else
		{
		   n = n + 1;
		}	   
	 }
   printf("After 10 votes: Mr. A has %d votes, Ms. B has %d votes, and %d votes for neither\n", a, b, n);

   return 0;
}

No matter what I input, I always get this result:

Code:
After 10 votes: Mr. A has 10 votes, Ms. B has 0 votes, and 0 votes for neither

I don't see how my counter is messed up?
 

SteveMeister

Hang out with Steve.
You're using the assignment operator = instead of the comparison operator ==, so temp is always being assigned to 1 and a is always incremented.
 
Back again with another question. I'm trying to wrap my head around recusive functions. One of my practice problems is: Asks the user for an integer input. sum the integers between 1 and that number. Must use a static variable for the accumulator.

Code:
static int sum(int z)
{

   printf("Please select a positive number:\n");
   scanf("%d\n", &z);
   
        if (z > 0)
        {
          return z + sum(z - 1);
        }
        else
        {
          return z;
        }
}

What happens is it just asking me to select a positive number. I've tried putting the

Code:
   printf("Please select a positive number:\n");
   scanf("%d\n", &z);

outside the function so it wouldn't be called every time, but that didn't solve it. The textbook gives a skint 2 page discussion/examples of recursion functions all of which are about factorials, not summation. What am I missing?
 

Kalnos

Banned
That exact function worked for me Blood.

lBhtd.png
 

Lathentar

Looking for Pants
Back again with another question. I'm trying to wrap my head around recusive functions. One of my practice problems is: Asks the user for an integer input. sum the integers between 1 and that number. Must use a static variable for the accumulator.

Code:
static int sum(int z)
{

   printf("Please select a positive number:\n");
   scanf("%d\n", &z);
   
        if (z > 0)
        {
          return z + sum(z - 1);
        }
        else
        {
          return z;
        }
}

What happens is it just asking me to select a positive number. I've tried putting the

Code:
   printf("Please select a positive number:\n");
   scanf("%d\n", &z);

outside the function so it wouldn't be called every time, but that didn't solve it. The textbook gives a skint 2 page discussion/examples of recursion functions all of which are about factorials, not summation. What am I missing?
You aren't using a static variable anywhere. Give us all the code if you need some help.
 
alright, full code from the review...bolded is the function in question.

Code:
#include<stdio.h>

//Declarations

void vote(int);
static int sum(int);
int exit(int);

int main ()
{

int choice;
int a,b,c = 0;

do
{
   printf("Please select one of the three options: (1) Voting Machine (2) Summation (3) Exit\n");
   scanf("%d", &choice);
  
      switch(choice)
      {
         case 1:
	   /*printf("Voting Machine\n");*/
	   break;
         case 2:
	   /*printf("Summation\n");*/
	   break;
         case 3:
	   /*printf("Exit\n");*/
	   break;
         default:
	   printf("Sorry, that is not a valid option.\n");
      }
}       
  while(choice != 1 && choice != 2 && choice != 3);

if(choice == 1)
   {
      vote(a);
   }
else if(choice == 2)
   {

      sum(b);
   }
else (choice == 3);
   {
      exit(c);
   }

return 0;

}


//Functions

//vote
void vote(int total)
{
	int a = 0; //vote for Mr. A
	int b = 0; //vote for Ms. B
	int n = 0; //vote for nobody
	int i = 0; //counter
	int x = 0; //tally

   for (i = 1; i <= 10; i++)
	{
	   printf("Please cast your vote: 1 for Mr. A or 2 for Ms. B\n");
	   scanf("%d", &x);
	   if (x == 1)
		{
		   a++;
		}
	   else if(x == 2)
		{
		   b++;
		}
	   else
		{
		   n++;
		}
	}
   printf("After 10 votes: Mr. A has %d votes, Ms. B has %d votes, and %d votes for neither\n", a, b, n);

   return;
}
[B]
//sum

static int sum(int z)
{
	      
      printf("Please select a positive number:\n");
      scanf("%d\n", &z);

        if (z > 0)
        {
          return z + sum(z - 1);
        }
        else
        {
          return z;
        }
}
[/B]
//exit
int exit(int e)
{
return;
}
 

maharg

idspispopd
Back again with another question. I'm trying to wrap my head around recusive functions. One of my practice problems is: Asks the user for an integer input. sum the integers between 1 and that number. Must use a static variable for the accumulator.

Code:
static int sum(int z)
{

   printf("Please select a positive number:\n");
   scanf("%d\n", &z);
   
        if (z > 0)
        {
          return z + sum(z - 1);
        }
        else
        {
          return z;
        }
}

What happens is it just asking me to select a positive number. I've tried putting the

Code:
   printf("Please select a positive number:\n");
   scanf("%d\n", &z);

outside the function so it wouldn't be called every time, but that didn't solve it. The textbook gives a skint 2 page discussion/examples of recursion functions all of which are about factorials, not summation. What am I missing?

You're missing how utterly retarded this question is on every level. God CS assignments make my heart ache.
 

Lathentar

Looking for Pants
You're missing how utterly retarded this question is on every level. God CS assignments make my heart ache.

Agreed. Let's teach people how to solve simple problems in the worst possible way.

Try this:
Code:
#include<stdio.h>

//Declarations

void vote(int);
int sum(int);
int exit(int);

int main ()
{

int choice;
int a,b,c = 0;

do
{
   printf("Please select one of the three options: (1) Voting Machine (2) Summation (3) Exit\n");
   scanf("%d", &choice);
  
      switch(choice)
      {
         case 1:
	   /*printf("Voting Machine\n");*/
	   break;
         case 2:
	   /*printf("Summation\n");*/
	   break;
         case 3:
	   /*printf("Exit\n");*/
	   break;
         default:
	   printf("Sorry, that is not a valid option.\n");
      }
}       
  while(choice != 1 && choice != 2 && choice != 3);

if(choice == 1)
   {
      vote(a);
   }
else if(choice == 2)
   {
      printf("Please select a positive number:\n");
      scanf("%d\n", &z);

      sum(b);
   }
else (choice == 3);
   {
      exit(c);
   }

return 0;

}


//Functions

//vote
void vote(int total)
{
	int a = 0; //vote for Mr. A
	int b = 0; //vote for Ms. B
	int n = 0; //vote for nobody
	int i = 0; //counter
	int x = 0; //tally

   for (i = 1; i <= 10; i++)
	{
	   printf("Please cast your vote: 1 for Mr. A or 2 for Ms. B\n");
	   scanf("%d", &x);
	   if (x == 1)
		{
		   a++;
		}
	   else if(x == 2)
		{
		   b++;
		}
	   else
		{
		   n++;
		}
	}
   printf("After 10 votes: Mr. A has %d votes, Ms. B has %d votes, and %d votes for neither\n", a, b, n);

   return;
}

//sum

int sum(int z)
{
        static int totalSum = 0;

        if (z > 0)
        {
          totalSum += z;
          sum( z - 1 );
        }
        else
        {
           printf( "Total sum: %d\n", totalSum );  
        }
}

//exit
int exit(int e)
{
return;
}
 

rpmurphy

Member
Yeah, the curveball is the static variable as the accumulator, which doesn't make much sense for recursion here. Otherwise you have the right idea for how recursion works! Essentially, the answer is that don't return anything because you're adding stuff into the static variable.

@Lathentar: you are declaring and initializing the static variable inside the recursive function.
 

maharg

idspispopd
It doesnt say the function has to be recursive. :p

But it's stupid regardless

I didn't even look at his code. I don't blame him for doing the wrong thing. I'd expect any competent programmer given this set of requirements to be confused and then just do something else.
 

BlueMagic

Member
Thanks to everyone for your help and sorry it took so long for me to answer, now that I'm working I hardly find time for this.

If you have to pass a CollisionEntity* around and you need to access say, bullet-specific data in the CollisionEntity, then you will have to do (dynamic_cast) downcasts regardless. You could do a switch statement like Haly suggested, or you could name your methods different things like HitBullet, HitPlayer, etc.

I almost wonder if you have a design issue, however. If it is just a question of "what type is the entity I just hit", you can implement a GetEntityType method in your CollisionEntity, and have every subclass return something different. That way you don't need any casts and you can implement a generic onCollision method.

If you find yourself needing to know implementation details of the thing you just collided with, I suggest that might be a design issue that would be better served by calling a method on the entity you collided with...though even that may require a downcast if it's a very entity-type-specific method.

I don't know if any of that was very good advice. :X

I too think it's a design issue. However I just couldn't seem to find a way to do it better (it occurred to me that I could have a GetEntityType kind of method where every class returns a code for identifying the class). I was just hoping there was a magical way of doing different methods for the hit with each class. This meaning I wouldn't have to implement a switch, just code onCollision(Bullet* entity) and it would automatically execute that method. I guess the switch way is the way to go now.
 

Haly

One day I realized that sadness is just another word for not enough coffee.
What is programmingGAF's opinion on the Singleton design pattern?

I used it in a team project last semester and I was floored by how simple it made everything. However, I can't help but feel that there is some kind of tradeoff for that convenience. I plan to use it in a personal project once I'm done with classes and I wanted to learn more about what I'm getting into. I should mention that this is all from the perspective of game programming.
 
What is programmingGAF's opinion on the Singleton design pattern?

I used it in a team project last semester and I was floored by how simple it made everything. However, I can't help but feel that there is some kind of tradeoff for that convenience. I plan to use it in a personal project once I'm done with classes and I wanted to learn more about what I'm getting into. I should mention that this is all from the perspective of game programming.
As with all things, use where appropriate. It's certainly better than a global in most cases where you only need one instance.
 
What is programmingGAF's opinion on the Singleton design pattern?

I used it in a team project last semester and I was floored by how simple it made everything. However, I can't help but feel that there is some kind of tradeoff for that convenience. I plan to use it in a personal project once I'm done with classes and I wanted to learn more about what I'm getting into. I should mention that this is all from the perspective of game programming.

Singletons really don't have much, if any, advantage over static classes that I can think of.
 

maharg

idspispopd
What is programmingGAF's opinion on the Singleton design pattern?

Get out of the habit of thinking of patterns as something you can have opinions on. Patterns are a description of existing practices, not a prescription or a technique. Understanding the way programs are structured is important, but trying to use 'design patterns' like building blocks, especially where you start talking about one somehow being 'better' than another, is just a recipe for bad code.

And, incidentally, static methods are an implementation of the 'singleton design pattern.' They are not what's usually called a singleton in C++, but they are singletons in the broader pattern sense.
 
Get out of the habit of thinking of patterns as something you can have opinions on. Patterns are a description of existing practices, not a prescription or a technique. Understanding the way programs are structured is important, but trying to use 'design patterns' like building blocks, especially where you start talking about one somehow being 'better' than another, is just a recipe for bad code.

And, incidentally, static methods are an implementation of the 'singleton design pattern.' They are not what's usually called a singleton in C++, but they are singletons in the broader pattern sense.

So true. The only time one design pattern is better than another design pattern is when it fits the needs of your particular program better than some other pattern does. It's not like you can pick one ahead of time and dictate that that is how everything should be done. You end up using the pattern that best solves your problem.
 
Status
Not open for further replies.
Top Bottom