• 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.

AcciDante

Member
Linkhero, so you only have to check the uppercase values, you can convert your character input to uppercase.
Code:
char first;
cin >> first;
first = toupper( first );
edited out something dumb >.>
 

poweld

Member
Zoramon089 said:
Hey quick question, can you simply assign pointers to other pointers or is there a special way to do it? For instance can I do

Code:
obj* ptr1 = sdfsdf; // Some assigment
obj* ptr2 = hrtrh;

ptr1 = ptr2;
Yes, you can assign pointers to each other. A pointer's value is a location in memory. When you do an assignment of `ptr1 = ptr2` the address stored in ptr2 overwrites the address stored in ptr1.
Linkhero1 said:
I fixed it with this, but idk how to shorten it cuz it looks ugly

Code:
if (_start != 'A')
		if(_start!= 'B')
			if(_start!= 'C')
				if(_start!= 'D')
					if(_start!= 'E')
						if(_start!= 'F')
							if(_start!= 'G')
								if(_start!= 'H')
									if(_start!= 'a')
										if(_start!= 'b')
											if(_start!= 'c')
												if(_start!= 'd')
													if(_start!= 'e')
														if(_start!= 'f')
															if(_start!= 'g')
																if(_start!= 'h')
																{
																cout << "Fail... ";
																exit(1);
																}
Oh... oh my.
Code:
if ((_start < 'A' || _start > 'H') || (_start < 'a' || _start > 'h')) {
    std::cout << "Fail... ";

    exit(1);
}
Characters can be implicitly converted into integers. Feel free to treat them as such when needed. This can be helpful in cases like this, when you are dealing with a series of consecutive letters.
 

deadbeef

Member
Linkhero1 said:
Fixed it...I was using Or logic instead of And

so it works now

Code:
if (first!= 'A' && first!= 'B' &&...

:D


lol I completely missed that. I noticed your expression being wrong: first != 'A' || 'B' || ...
 

ha1f

Member
Zoramon089 said:
Hey quick question, can you simply assign pointers to other pointers or is there a special way to do it? For instance can I do

Code:
obj* ptr1 = sdfsdf; // Some assigment
obj* ptr2 = hrtrh;

ptr1 = ptr2;
yes


Linkhero1 said:
I fixed it with this, but idk how to shorten it cuz it looks ugly
Code:
lol
this should work (i think). im not sure how c++ plays with ascii chars.
Code:
if ( _start < 'A' /* 65 */ || (_start > 'H' /* 72 */ && _start < 'a' /* 97 */ ) || _start > 'h' /* 104*/ )
    return exit(1);
 

Linkhero1

Member
deadbeef said:
lol I completely missed that. I noticed your expression being wrong: first != 'A' || 'B' || ...
Yeah I really rushed through it, should have just kept messing around before I asked here. thanks nonetheless. :D
 

Toby

Member
Couldn't you use the characters decimal ascii value along with relational operators to shorten that up?
 

deadbeef

Member
Characters can be implicitly converted into integers. Feel free to treat them as such when needed. This can be helpful in cases like this, when you are dealing with a series of consecutive letters.

This is true, but when suddenly E and C are no longer valid choices, then it could be argued that it is easier to maintain the code if you just have to remove those expressions. But I'm not necessarily making that argument.
 

poweld

Member
deadbeef said:
This is true, but when suddenly E and C are no longer valid choices, then it could be argued that it is easier to maintain the code if you just have to remove those expressions. But I'm not necessarily making that argument.
Right, but I highly doubt Link's code is meant to be maintained for long ;)

Anyhow, in that case you'd set a lowercaseLowerBound char, lowercaseUpperBound, uppercaseLowerBound, and uppercaseUpperBound, and compare to those. Then you're nice and extensible.
Code:
char lowercaseLowerBound = 'a';
char lowercaseUpperBound = 'h';
char uppercaseLowerBound = 'A';
char uppercaseUpperBound = 'H';
if ((_start < lowercaseLowerBound || _start > lowercaseUpperBound) || 
    (_start < uppercaseLowerBound || _start > uppercaseUpperBound)) {
    std::cout << "Fail... ";

    exit(1);
}
 

maharg

idspispopd
poweld said:
Characters can be implicitly converted into integers. Feel free to treat them as such when needed. This can be helpful in cases like this, when you are dealing with a series of consecutive letters.

Characters *are* integers, nothing more and nothing less. It probably sounds like splitting hairs, but distinctions like this are important and fundamental.
 

poweld

Member
maharg said:
Characters *are* integers, nothing more and nothing less. It probably sounds like splitting hairs, but distinctions like this are important and fundamental.
Yep, I guess I was just trying to keep it simple, not that that makes much sense now that I'm not tired.
 

fenners

Member
Zoramon089 said:
Hey quick question, can you simply assign pointers to other pointers or is there a special way to do it? For instance can I do

Code:
obj* ptr1 = sdfsdf; // Some assigment
obj* ptr2 = hrtrh;

ptr1 = ptr2;

As other people have said, yes, you can do assignment with pointers - pointers just contain a memory address. That's where the fun/trouble comes into it - in your example above, what are you wanting to be assigned? Because you're just sticking the memory address of sdfsdf into the ptr2's location. No change was made to either sdfsdf or hrtrh. Essentially you've got two pointers to the first object now.
 
Having some pointer problems that I don't really understand. This is just a small snippet of my code, shortened for the sake of this post, but including everything relevant.


Code:
int id=0;
int i;
vector<*myClass> theList;

while(true) // My program is looping but I don't feel like typing out everything else
{
if(theList.empty())
     theList.push_back(&myClass(id));
else
{
     printf("id %i", theList[0]->getId())
     theList[0] = &myClass(id));
}

So as you can see I have a class I created named myClass which takes in an int as a parameter and simply saves it into an int field in the class. It also has a function called getId() which simply returns that field. The problem here is that when I print out the int I get

Code:
id -858993460

Which I don't understand

}
 

Zeppu

Member
I'm not understanding &myClass(id).

What exactly are you doing there?

If that's your instantiation of the class, it's running out of scope and getting destroyed so you're accessing invalid memory, thus why you're getting the random integer.

Edit: If what I said is correct then:

myClass * whatever = new myClass(id);
theList.push_back(whatever);

should work for you.

just remember you need to manually delete all instances of myClass if you're creating them on the heap.
 
josephdebono said:
I'm not understanding &myClass(id).

What exactly are you doing there?

If that's your instantiation of the class, it's running out of scope and getting destroyed so you're accessing invalid memory, thus why you're getting the random integer.

Yeah, reading more about it, I kind of thought that was the issue but I did this as well and got the same problem.

Code:
int id=0;
int i;
vector<*myClass> theList;

while(true) // My program is looping but I don't feel like typing out everything else
{
if(theList.empty())
{
     myClass m = myClass(id);  
     theList.push_back(&m);
}
else
{
     printf("id %i", theList[0]->getId())
     myClass m = myClass(id);  
     theList[0] = &m);
}

}
 

Zeppu

Member
Zoramon089 said:
Yeah, reading more about it, I kind of thought that was the issue but I did this as well and got the same problem.

Code:
code

}


You need to new it.

myClass * whatever = new myClass(id);
theList.push_back(whatever);

And as stated above, you have to manually delete the instances when clearing the vector.

Remember, unless you're returning or storing the object itself (which you aren't since you're only storing a pointer to the object) it will get destroyed when you leave scope.
 
THANKS
That was the problem. Man...switching from java to C++...syntactically it's not too different but all the small differences with pointers and references make a HUGE difference in what works and what doesn't
 

poweld

Member
Zoramon089 said:
Having some pointer problems that I don't really understand. This is just a small snippet of my code, shortened for the sake of this post, but including everything relevant.


Code:
int id=0;
int i;
vector<*myClass> theList;

while(true) // My program is looping but I don't feel like typing out everything else
{
if(theList.empty())
     theList.push_back(&myClass(id));
else
{
     printf("id %i", theList[0]->getId())
     theList[0] = &myClass(id));
}

So as you can see I have a class I created named myClass which takes in an int as a parameter and simply saves it into an int field in the class. It also has a function called getId() which simply returns that field. The problem here is that when I print out the int I get

Code:
id -858993460

Which I don't understand

}
Code:
int id=0;
int i;
vector<myClass*> theList; // the star goes afterward to indicate a pointer of type myClass

while(true) // My program is looping but I don't feel like typing out everything else
{
if(theList.empty())
     theList.push_back(new myClass(id)); // this allocates memory for and initiates an instance of myClass, and returns a pointer to it
else
{
     printf("id %i", theList[0]->getId())
     // theList[0] = &myClass(id));    // commented this line, since it doesn't make sense to me what you're even trying to do here.
}
 

Zeppu

Member
I'm editing after I post each reply so you may have missed some of what I'm saying. Now, I understand what you're doing but I don't know if you're doing this to learn or for an actual 'useful' task. In reality, I see no reason for you to storing the pointers there, so:

vector<myClass> theList;

theList.push_back(myClass(id));

theList[0].getId();

would work just as well and remove the unnecessary pointer headaches.
 
No, they need to be pointers for other functionality in the program. Mainly because myClass is a derived class of another class and sometimes I need to cast it as that based class. I can only use the dynamic_cast if it's a pointer
 
josephdebono said:
I'm editing after I post each reply so you may have missed some of what I'm saying. Now, I understand what you're doing but I don't know if you're doing this to learn or for an actual 'useful' task. In reality, I see no reason for you to storing the pointers there, so:

vector<myClass> theList;

theList.push_back(myClass(id));

theList[0].getId();

would work just as well and remove the unnecessary pointer headaches.

I tend to agree with this most of the time, but you need to understand the difference. Sometimes this can lead to significantly better performance (not having your accesses go through a pointer is significantly better for cache-locality), sometimes it can lead to significantly worse performance (vector operations often result in lots of copies being made, if you have a non-trivial copy-constructor, or even if your objects are just large, this can be a big performance hit), sometimes it's flat out broken (e.g. if your destructors free external resources like file handles, sockets, etc), and sometimes it isn't even possible (i.e. if you need to rely on polymorphic behavior).


Zoramon089 said:
No, they need to be pointers for other functionality in the program. Mainly because myClass is a derived class of another class and sometimes I need to cast it as that based class. I can only use the dynamic_cast if it's a pointer
For future reference, if you're using dynamic_cast<> chances are you're doing somethign wrong. Keep going with it while you're still learning the language, but just keep it in the back of your mind that there's almost certainly a better way.
 
cpp_is_king said:
For future reference, if you're using dynamic_cast<> chances are you're doing somethign wrong. Keep going with it while you're still learning the language, but just keep it in the back of your mind that there's almost certainly a better way.

Yeah, i've tried a number of ways already. I even consulted this topic earlier and that ended up being the method that worked best. I basically have a vector of a base class and I need to add a bunch of derived classes to it, so I can loop through all of them and call a fucntion in the base class on all of them.

That works just fine but sometimes I need to call a function specific to a base class (which i can determine accurately based on the index in the vector). When i tried a simple cast of (derivedClass)list[index] it kept giving me errors about there being no way to cast to the derived class.
 

fenners

Member
Zoramon089 said:
Yeah, i've tried a number of ways already. I even consulted this topic earlier and that ended up being the method that worked best. I basically have a vector of a base class and I need to add a bunch of derived classes to it, so I can loop through all of them and call a fucntion in the base class on all of them.

That works just fine but sometimes I need to call a function specific to a base class (which i can determine accurately based on the index in the vector). When i tried a simple cast of (derivedClass)list[index] it kept giving me errors about there being no way to cast to the derived class.

Didn't we go over this earlier in the thread?
 

rexor0717

Member
Hey people, I'm back again. I'm trying to find a good way to read in file, but have it exclude all whitespace and punctuation. I'm looking at istream right now, but I don't see a way that I can make it exclude punctuation. Do you know of something else I could use, or am I just not looking in the right place?
 

poweld

Member
rexor0717 said:
Hey people, I'm back again. I'm trying to find a good way to read in file, but have it exclude all whitespace and punctuation. I'm looking at istream right now, but I don't see a way that I can make it exclude punctuation. Do you know of something else I could use, or am I just not looking in the right place?
If you're just looking for alpha characters (a-zA-Z) you could just use istream and check the retrieved characters to see if they're <45 ('A') or >122 ('z')

edit: to be more clear:

Code:
char c;
while(whatever) {
    instream.get(c);
    if (c >= 'A' || c <= 'z') {
        // do what you will with c
    }
}
 

Lathentar

Looking for Pants
Anyone do Google CodeJam last night/today? It was a lot of fun, 3/4 questions were video game references.

The last two were kinda mean on Google's part though. Couple of questions that appear very difficult at first yet ended up having super trivial answers.
 

poweld

Member
Lathentar said:
Anyone do Google CodeJam last night/today? It was a lot of fun, 3/4 questions were video game references.

The last two were kinda mean on Google's part though. Couple of questions that appear very difficult at first yet ended up having super trivial answers.
Unfortunately, no. Do they host these often? I've never looked into it, to be honest.
 

poweld

Member
Lathentar said:
Once a year. Yesterday was the qualifier round.

You can still do all the questions.
Nice, thanks. Did the first two (really digging the references :) ) but I'm a little stumped by how to approach the 3rd.

I know that for all order bits, there must be an even number of said bit (or 0) to keep the kid from crying. As for finding out the most lucrative combination for the smart kid, I'm guessing I just need to come up with a search tree that finds the most lucrative combination of numbers that contains an odd count for all order bits (that aren't 0)

But the way you made it sound, perhaps I'm overthinking it?
 

BlueMagic

Member
So I have 2 functions with the following prototypes:

Code:
void functionA(const char* str, ...);

bool functionB(int,int,const char*,...);

bool functionB(int a,int b, const char* string,...){
     //code 
     //call of functionA();
     //return true;
}

(functionB uses functionA).

Is there any way I can directly pass the ellipsis arguments from functionB to functionA?

Thank you very much, I appreciate the help.
 
poweld said:
Nice, thanks. Did the first two (really digging the references :) ) but I'm a little stumped by how to approach the 3rd.

I know that for all order bits, there must be an even number of said bit (or 0) to keep the kid from crying. As for finding out the most lucrative combination for the smart kid, I'm guessing I just need to come up with a search tree that finds the most lucrative combination of numbers that contains an odd count for all order bits (that aren't 0)

But the way you made it sound, perhaps I'm overthinking it?

I didn't try that one, but the Goro Sort problem was pretty cool. I did it by first proving a mathematical formula for the optimal strategy and from there the actual algorithm is trivial. But convincing yourself that the optimal strategy is in fact optimal, and being able to compute the expected number of trials assuming you do use the optimal strategy is not immediately obvious.

I wonder if other people solved it a different way than i did though.
 

Linkhero1

Member
I'm writing a code that transverses through a directory you choose and searches for a file you specify. I'm trying to write something to display the directory the file is in. Say for example someone selects C:\ as the root directory and then readme.TXT as the file they're searching for they code will transverse through folders until it finds it. I'm having trouble returning the path to display.

Code:
        item_iterator m1;

	pair<item_iterator, item_iterator> range = items.equal_range(item);

	for (m1 = range.first; m1 != range.second; ++m1)
	{
		std::cout << "Directory Location: " << (*m1).second << endl;
	}
items is multimap i declared earlier and item is just the name of the file the user is searching for. I am able to display how many folders and items are in the directory but I'm unable to produce a path to display.

Edit: nvm it's because of a function I'm using not working properly. I'm not sure why though but I guess I'll spend some time debugging it.
 

Slavik81

Member
BlueMagic said:
So I have 2 functions with the following prototypes:

Code:
void functionA(const char* str, ...);

bool functionB(int,int,const char*,...);

bool functionB(int a,int b, const char* string,...){
     //code 
     //call of functionA();
     //return true;
}

(functionB uses functionA).

Is there any way I can directly pass the ellipsis arguments from functionB to functionA?

Thank you very much, I appreciate the help.
No. However, you can pass the va_list.
 

poweld

Member
Complex Shadow said:
Can someone explain me the diffrence between references and pointers.
A reference can never be reseated, but a pointer can.

Code:
int& someNumRef = someNum;
someNumRef = 5; // someNum is now equal to 5

int* someNumPtr = &someNum;
*someNumPtr = 10; // someNum is now equal to 10
someNumPtr = &someOtherNum;
*someNumPtr = 20; // someOtherNum is now equal to 20
 
poweld said:
A reference can never be reseated, but a pointer can.

Code:
int& someNumRef = someNum;
someNumRef = 5; // someNum is now equal to 5

int* someNumPtr = &someNum;
*someNumPtr = 10; // someNum is now equal to 10
someNumPtr = &someOtherNum;
*someNumPtr = 20; // someOtherNum is now equal to 20

Also a reference cannot be NULL, but a pointer can.
 

maharg

idspispopd
Put more in terms of *why* they're different rather than the specific details of how, a reference acts like a value. References also imply a lack of ownership over the underlying resource.

So basically, if you just want to avoid copying something when you pass it into a function (because it's heavy or has non-copying semantics), and intend to treat it as a value, you should use a reference.
 

poweld

Member
maharg said:
Put more in terms of *why* they're different rather than the specific details of how, a reference acts like a value. References also imply a lack of ownership over the underlying resource.

So basically, if you just want to avoid copying something when you pass it into a function (because it's heavy or has non-copying semantics), and intend to treat it as a value, you should use a reference.
I like how you put it.
 
Hey, I'm looking over past papers for my C++ exam next week and can't find the answer for this question.

In C++ how may bytes of memory are occupied by an array of 150 integers and an array of 150 character pointers.

Thanks in advance.
 

poweld

Member
Zombie Lyle said:
Hey, I'm looking over past papers for my C++ exam next week and can't find the answer for this question.

In C++ how may bytes of memory are occupied by an array of 150 integers and an array of 150 character pointers.

Thanks in advance.
Integers are 4 bytes long, so 150x4 = 600bytes
Characters are 1 byte, so 150x1 = 150bytes
 

Rapstah

Member
I'm getting std::eek:ut_of_range errors concerning a string check function in my program. For everyone's sanity I'm not going to post the actual application here but what usually causes this? I have a ton of loops going through entire strings in the function in question - should I be looking for places where it tries to look at what character there is at a position that isn't defined in the string?
 

poweld

Member
Rapstah said:
I'm getting std::eek:ut_of_range errors concerning a string check function in my program. For everyone's sanity I'm not going to post the actual application here but what usually causes this? I have a ton of loops going through entire strings in the function in question - should I be looking for places where it tries to look at what character there is at a position that isn't defined in the string?
You should be looking for places where you are looking at index positions in your string, for example when you use the bracket operator (e.g. myString[10]) or at (e.g. myString.at(10)). The error is being thrown because you're trying to access an index in the container that does not exist.
 

Rapstah

Member
poweld said:
You should be looking for places where you are looking at index positions in your string, for example when you use the bracket operator (e.g. myString[10]) or at (e.g. myString.at(10)). The error is being thrown because you're trying to access an index in the container that does not exist.
I figured that, good to know I'm at least thinking right at some level, ha.
 

deadbeef

Member
poweld said:
Integers are 4 bytes long, so 150x4 = 600bytes
Characters are 1 byte, so 150x1 = 150bytes

Isn't this architecture dependent? Wouldn't it be more correct to use the sizeof operator?
 

Tigel

Member
Zombie Lyle said:
Hey, I'm looking over past papers for my C++ exam next week and can't find the answer for this question.

In C++ how may bytes of memory are occupied by an array of 150 integers and an array of 150 character pointers.

Thanks in advance.

deadbeef said:
Isn't this architecture dependent? Wouldn't it be more correct to use the sizeof operator?
Yeah. A pointer is 32 bits (4 bytes) on a 32 bits architecture and 64 bits (8 bytes) on a 64 bits architecture.

If the question is on a 32 bits architecture, then 150 integers and 150 char pointers use the same amount of memory (150 * 4 bytes).
 

poweld

Member
Tigel said:
Yeah. A pointer is 32 bits (4 bytes) on a 32 bits architecture and 64 bits (8 bytes) on a 64 bits architecture.

If the question is on a 32 bits architecture, then 150 integers and 150 char pointers use the same amount of memory (150 * 4 bytes).
Yeah, I guess I just figured if it's asking for the size of an int they may be assuming 32bit. Also, good eye, I didn't see that it was char pointers, not char's.

In that case an int and a pointer to anything will always scale to the architecture, be it 32 or 64 bit.
 
Is a pointer always 4 bytes for an int, char or float?

Also guys, I hate to ask loads of questions but I'm useless at C++. I don't know how to use a vector as an array. The question is below.

Write the C++ code to dynamically create a vector of 100 long integers. Explain how you could use this block of memory as a two dimensional array of 10 by 10 long integers. Also give the code to release the vector.
 
Status
Not open for further replies.
Top Bottom