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

Programming |OT| C is better than C++! No, C++ is better than C

Oh snap that makes sense. And after dereferencing getsuit/rank/name it's working! Feels like wizardry! Makes me feel a lot better. Now I need to have a destructor at the end of the program so the pointers get removed or whatnot right?
Yeah, you'd have to call delete on each of those pointers - the vector won't know what to do with them otherwise.
 

Haly

One day I realized that sadness is just another word for not enough coffee.
If you decide to use the erase() method built into vector, ALWAYS ERASE FROM BACK TO FRONT.

If you erase() anything other than the last element in the vector, it'll automatically shift everything after the index you just erased one index to the front, causing you to erase only half your vector and possibly call erase() on non-existent elements as well.
 
So I'm taking a ruby on rails class right now where we have to build a website like delicious on a vps. It's a lot of fun so far but rails is a little tricky and my teacher isn't teaching ruby at all :/. Teachers sometime I swear. But I love doing Web stuff. It's what my internship was, what my current job is, and what I do when I am a consultant. Anyone else have any experience in ruby or rails? They useful? Better than php?
 

Lathentar

Looking for Pants
If you decide to use the erase() method built into vector, ALWAYS ERASE FROM BACK TO FRONT.

If you erase() anything other than the last element in the vector, it'll automatically shift everything after the index you just erased one index to the front, causing you to erase only half your vector and possibly call erase() on non-existent elements as well.

This isn't quite the best advice. If you're going to erase everything just use the clear method. If you do use the erase method, you just need to know how to modify your loop to compensate for the return type. erase invalidates all iterators of the loop, which is why it returns a valis iterator to prevent skipping elements.

Code Example:
Code:
for (std::vector<int>::iterator iter = list_of_ints.begin(); iter != list_of_ints.end();)
{
   if ( should_erase( *iter ) )
   {
      iter = list_of_ints.erase( iter );   // Returns an iterator to the next element
   }
   else
   {
      ++iter; // increment iterator as we normally would
   }
}

He is right in that it is preferred to erase elements from vectors back to front as it will be constant time with no copying required. If ordering isn't important to your vector, you can use the unordered erase trick where you swap the element you want to erase with the element in the back of the vector and then erase from the end. Which is still a constant time erase.
 

Exuro

Member
Alright, so I can just use clear to remove the content in the vector down to zero, but it's still allocated the memory correct? So if I just wanted to remove vector couldn't I just use delete or would I still need to use erase first?

Also, I think I know what I want to try out now. I want to make some sort of container/inventory that holds multiple decks of cards. Have cards in decks be accessed and viewed. Be able to swap cards from one deck to another, be it trading it for another or just removing and adding to another. I think that's a good start. I'll need to make an inventory class or something. Going to take some time thinking about how to do that.
 

Lathentar

Looking for Pants
Alright, so I can just use clear to remove the content in the vector down to zero, but it's still allocated the memory correct? So if I just wanted to remove vector couldn't I just use delete or would I still need to use erase first?

erase doesn't call delete on any of the elements. It won't free up the memory you allocated by calling new. You'll need to do a for loop over all of the elements in the list and call delete on each pointer. Then you can just call clear on the vector to remove all the pointers (though if this is in the destructor, that's not required and you just end up with a needless function call).

Slavik had the better approach where if you kept your code as it was (prior to using pointers) you could have just returned a reference to each card in your GetCard() function and not worried about any memory management. Another alternative would be to use a smart pointer such as std::shared_ptr, then you wouldn't need to worry about memory management.
 

Viewt

Member
Hey, Programmer-GAF!

So after years of being on the product spec / management side, I'd really like to develop some programming chops. I'm not trying to switch career paths or anything, but I think increasing my technical know-how would probably make me a more effective Producer/Product Manager.

So the downside here is that I'm a complete novice. For completely random reasons I've decided to roll with Python to start (though I'm open to suggestions if there's another language that'd be better) and I've finished most of what's up on CodeAcademy. What I'd really like to do is start building something, just to put those basics into practice. So I was wondering if any of you have some advice for a lowly beginner who's looking for good exercises to repeat ad nauseum until it starts to stick.
 

Exuro

Member
Slavik had the better approach where if you kept your code as it was (prior to using pointers) you could have just returned a reference to each card in your GetCard() function and not worried about any memory management.
So for that would I use Card& getCard() instead of Card* getCard()?
 

Lathentar

Looking for Pants
So for that would I use Card& getCard() instead of Card* getCard()?

Yes. For vectors (and all (?) stl containers) operator[] returns a reference.

Make sure anything using getCard stores the return value as a reference.

Card myCard = deck.getCard();
This will cause a copy to be made and any changes will not be reflected in the card in the deck.
 

Exuro

Member
Yes. For vectors (and all (?) stl containers) operator[] returns a reference.

Make sure anything using getCard stores the return value as a reference.

Card myCard = deck.getCard();
This will cause a copy to be made and any changes will not be reflected in the card in the deck.
Alright I'm almost there. Figured out the reference operator needed to be placed after the <Card> in the vector. Only error I'm getting is that I'm getting an uninitialized reference member in the constructor.

EDIT: Card myCard is just going to get the value returned by getCard right? How does that change the card values in the vector? How do I initialize and reference the vector?

Ugh this vector referencing/pointing is rough. Would I have to do the same work with an array?
 

Lathentar

Looking for Pants
Alright I'm almost there. Figured out the reference operator needed to be placed after the <Card> in the vector. Only error I'm getting is that I'm getting an uninitialized reference member in the constructor.

EDIT: Card myCard is just going to get the value returned by getCard right? How does that change the card values in the vector? How do I initialize and reference the vector?

Ugh this vector referencing/pointing is rough. Would I have to do the same work with an array?

Your vector is still a vector of Card (std::vector<Card>) not std::vector<Card&>. You would still need to do the same work with an array.

Just takes some time and experience to understand it. Knowing the different ways to store, pass and return types is very important to writing safe and efficient C++.

EDIT: Card & myCard = deck.getCard(); myCard is now essentially a dereferenced pointer to the card in the deck. No copying is done.
 

Exuro

Member
Your vector is still a vector of Card (std::vector<Card>) not std::vector<Card&>. You would still need to do the same work with an array.

Just takes some time and experience to understand it. Knowing the different ways to store, pass and return types is very important to writing safe and efficient C++.

EDIT: Card & myCard = deck.getCard(); myCard is now essentially a dereferenced pointer to the card in the deck. No copying is done.
Thanks. Things kind of clicked with pointing and dereferencing. I'll be fiddling around with my basic code.
 

Croc

Banned
So guys, I'm completely new to programming. I'm taking a python class on Coursera right now and I am really enjoying it. I'm also at a point in my life where I'm not really sure what I want to do. I'm kind of thinking of learning programming to bring that in as an option for some kind of career in the future.

I was just at a used book store today and ended up picking this up cause it was just a few bucks. As I said I don't really know anything about programming, so I guess what I'm asking is, is C++ a good language to learn in addition to Python, and is it one that is very adaptable to use in lots of different jobs and such? I haven't even started reading that book so I'm not committing to learning it yet.
 

wolfmat

Confirmed Asshole
So I'm taking a ruby on rails class right now where we have to build a website like delicious on a vps. It's a lot of fun so far but rails is a little tricky and my teacher isn't teaching ruby at all :/. Teachers sometime I swear. But I love doing Web stuff. It's what my internship was, what my current job is, and what I do when I am a consultant. Anyone else have any experience in ruby or rails? They useful? Better than php?

I have the impression that I'm one of the few drinking the Rails Kool-Aid, lol. Built a couple of sites and modules with it. I'd always pick it over PHP myself, without second thought.
I think it's down to preference because both languages basically can do the same things. But I enjoy programming in Ruby a lot, and Rails has good libraries.
And I get better results faster, can develop from interface down without hassle, for example, which makes a considerable (positive) difference in terms of the road from prototype to product. But as always with languages, YMMV

Anything specific you're having trouble with?
 

hateradio

The Most Dangerous Yes Man
You should read The Book of Ruby to get a bit of info on Ruby itself, and if you have time, read The Ruby Programing Language.

I was reading the first one, and read about 80 pages. Then someone recommended me the second one. I'm currently half way through it.


As for my own opinion, I haven't done anything with Ruby yet, but I'm already falling in love with it. PHP is fine if you use a framework, but the language itself leaves so much to be desired.
 

Ledsen

Member
So if one wants to get into making their own games, is XNA still worth going for? I've been reading some of the worrisome news about XNA and W8... if the answer is no, then what do you recommend I learn instead?
 

qwerty2k

Member
Hopefully this is a reasonable place to place this request.

Can anyone recommend any books on good coding practices (i'm mainly using c#/asp.net)?
 

Lathentar

Looking for Pants
So if one wants to get into making their own games, is XNA still worth going for? I've been reading some of the worrisome news about XNA and W8... if the answer is no, then what do you recommend I learn instead?

Is this a game for private usage? Then go for it. If you want to make a game for release, probably best looking somewhere else. There is an indie game thread somewhere, just search for it.
 
So I wake up during a storm this morning at 7 AM with a bunch of close lightning strikes, and in my grogginess, I'm laying there chastising myself because I didn't properly decouple the lightning and thunder from the storm so that I could write effective unit tests.
 

blanco21

Member
I'm starting off my first internship as a Java programmer (web automation, TestNG so far) and was wondering if you guys could recommend some books I could read on my 1+ hr. train ride to the office. I'm already into reading Effective Java, but some stuff isn't sticking as well as I'd like (usually I can get almost everything to stick w/o actually implementing it). I haven't had any work experience, but I think it I did pretty good/great throughout college. I think the best way to describe my situation is that I'm adept in the core mechanics of Java, but in the dark on various APIs, frameworks, etc. I really want to excel and I think it's within the realm of possibility.

Anything you guys throw out there I'll probably pick up off Amazon. I just found this thread, but I'm enjoying reading it so far. Hopefully I can contribute in the future.

Thanks.

edit: These are some I was looking at:

Java Complete Reference 8e by Oracle

Java in a Nutshell 5e (O'reilly) << from 2005...
 
First off, don't worry about having programming experience going into a degree in CS. It would be nice, but I didn't have any and I'm getting along fine 2 years later. Most all intro CS courses go over programming fundamentals before delving deep into the actual theoretical and mathematical stuff.

If you want to start now, I'd probably look at Python to get a feel for how things work. If you want to have fun, you could start out with C/C++, both are fairly unforgiving, but they tend to be more 'lower level' high level languages. They are both extremely flexible, but will allow you to shoot your foot off, or so they say.

I personally went into the major kind of knowing what I was getting into, but I had no programming experience whatsoever, and I've been fine with picking things up and understanding them.

A little late perhaps, but this is really reassuring and sounds like great advice too. Gonna get started on this when I get some free time this week. Thanks :)
 

Lkr

Member
i have a class lets call it blah. i have set up my public and private declarations. i have two constructors: blah() and blah(int realx, int realy). so when i pass those values into the constructor of that size, i want to be able to reuse those values. i have declared a private int of those names, but it doesn't work. how should i do this? i'll try to write the code here to make more sense:

Code:
class blah{
public:
  blah();
  blah(int realx, int realy);
  random member functions

private:
 int realx;
 int realy;

}

constructor definitions, etc

int main()
{
  blah(5,3);
  return 0;
}

tl;dr i want to use those numbers(5 and 3 in this case) to set sizes in member functions, but am clueless.

nvm i actually figured this out. my new problem is unary operators not allowing me to call a class object by reference
 

VoxPop

Member
Flash? Isn't that for media players?

Start with the basics though. HTML and CSS. Then Javascript, theres a bunch of scripts out there that are ready to use to make a website look better. And don't use w3schools.

EDIT: Oh, flash.... Yeah, I don't think anyone really uses that for web design anymore.

lorebringer said:
It depends on if your goal is to create a site for a specific purpose or if you want to learn about web development. If you just want to create a site and forget about it, something like Concrete or WordPress is a good place to start. If you want to learn properly I can go hunt down some more involved resources to get you started.

Oh yeah, and if you are interested in learning web development properly, just never use flash, that's one other problem solved.

I actually picked up a book today on HTML/CSS. I've been using a bit of codecademy and its been decent. Trying to learn everything as fast as possible because I have a quite a bit of website ideas I want to start on. Thanks again~
 

Chris R

Member
Feel free to post any questions you do have on html/css. Even though web sites aren't programming per say there are enough of us here that dabble in both who are willing to help. I'm actually starting to work on my personal portfolio website since I guess people who are into web development should have something of the sort.
 
I'm going through Learning Python the Hard way, and i'm stuck on exercise 35.

Code:
while True:
        next = raw_input("> ")

        if next == "take honey":
            dead("The bear looks at you then slaps your face off.")
        elif next == "taunt bear" and not bear_moved:
            print "The bear has moved from the door. You can go through it now."
            bear_moved = True
        elif next == "taunt bear" and bear_moved:
            dead("The bear gets pissed off and chews your leg off."
        elif next == "open door" and bear_moved:
            gold_room()
        else:
            print "I got no idea what that means."

this is copied straight from the book, but i'm getting this syntax error

Code:
File "ex35.py", line 37
   elif next == "open door" and bear_moved:
      ^
SyntaxError: invalid syntax

what is wrong with this?? i copied it out of the book verbatim but i keep getting this message!
 

tmdorsey

Member
Just an FYI, I just got an email from Codecademy stating they now have a Ruby course. This is perfect timing for me since I've been trying to learn Ruby on Rails for work.
3AQmK.gif
 

Lkr

Member
i need to error check for the user input. the user must input integers. how can i use a while loop to make sure that they can't input letters or shit? i know that when doing a number that has to be greater than 0 for example, it is simply while(int < 0) and then prompt them to re-enter. i don't know what to do for this, however.
 

FillerB

Member
i need to error check for the user input. the user must input integers. how can i use a while loop to make sure that they can't input letters or shit? i know that when doing a number that has to be greater than 0 for example, it is simply while(int < 0) and then prompt them to re-enter. i don't know what to do for this, however.

Which language and how is the input done?
 

Kalnos

Banned
i need to error check for the user input. the user must input integers. how can i use a while loop to make sure that they can't input letters or shit? i know that when doing a number that has to be greater than 0 for example, it is simply while(int < 0) and then prompt them to re-enter. i don't know what to do for this, however.

Use a boolean (keyword depends on language):

Code:
bool validInput = false;

while (validInput == false)  
{
      **get input**
      **check if it's valid**
      **if it is then set validInput = true, otherwise continue looping**
}

Alternatively, you could use integers:

Code:
int validInput = 0;

while (validInput == 0)  
{
      **get input**
      **check if it's valid**
      **if it is then set validInput = 1, otherwise continue looping**
}
 

BHZ Mayor

Member
i need to error check for the user input. the user must input integers. how can i use a while loop to make sure that they can't input letters or shit? i know that when doing a number that has to be greater than 0 for example, it is simply while(int < 0) and then prompt them to re-enter. i don't know what to do for this, however.

You could use regular expressions to do the actual validation.
 
Today I was particularly productive: 0 lines of usable code in five hours. Oh well, at least I got the grasp of what was wrong/what I have to do.

I am currently fixing other peoples programs at school as a sidejob.
 

BHZ Mayor

Member
Or you could look whether the ascii-value of the latest inputted character is between 48 and 57.

This is almost "mind blown" status for me. I would have never thought of checking ascii values as a validation option.

Edit: And it seems perfect for the situation described below.
 

Aurongel

Member
I have an assignment in my class that requires me to write a program that reads in an external file and prints out how many characters are in each line along with a few other statistics.

Sounds simple enough but I can't seem to wrap my head around navigating external files beyond just opening them with the fstream function. Any tips or pointers in the right direction?
 

Slavik81

Member
I have an assignment in my class that requires me to write a program that reads in an external file and prints out how many characters are in each line along with a few other statistics.

Sounds simple enough but I can't seem to wrap my head around navigating external files beyond just opening them with the fstream function. Any tips or pointers in the right direction?

I'm not particularly familiar with C++ standard streams, but it sounds like you want to read in lines using get to retrieve each line. You would use the overload that takes a stream buffer by supplying a string buffer.

After retrieving each line, you could examine the string and store any statistics you wanted about it. After processing every line in the file, do your final processing and output on the statistics you gathered.
 

FillerB

Member
C++ an cin one at a time to a part of an array

Instead of using cin you might look into scanf.

Note that the below example might not work. I don't have a compiler at hand to check it and it's been a while since I last used C++.

Code:
int i;
printf ("Enter integers one by one, any other value to quit.");
while(scanf ("%d",&i)>0){
	#put your number into your array#
}
 
Guys, I'm watching these C++ videos on http://thenewboston.org and he is explaining his code using Codeblocks. But I'm using Mac and have Xcode installed. It took me ages to find a console project tbh.

Anyhow do you recommend me continuing using Xcode or to try and install Codeblocks on my Mac?
 

d[-_-]b

Banned
need a little help with refactoring, essentially killing my ugly/spaghetti code
Code:
lManga = new Manga();
url = new URL(ele.get(i).attr("abs:href"));
lManga.setTitle(ele.get(i).text().replaceAll("\"", "").replace("'", ""));
lManga.setIndexLink(url.toString());
System.out.println(lManga.getTitle());
Document docdata2 = Jsoup.parse(url, 5000);
String ogImage = getMetaTag(docdata2, "og:image");
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(ogImage);
if (m.find()) {
	lManga.setID(Integer.valueOf(m.group()));
}
What techniques do you guys use...
 
Top Bottom