• 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

RobertM

Member
Does anyone have a good solution for Xmodem in C#? I keep getting NACKs using checksum and crc, and i cant seem to be able to find a library for xmodem
 
Are you sure it's not a backface culling problem? glDisable(GL_CULL_FACE)
Does it work with untextured quads?
Does it work with triangles?

I solved it. It doesn't matter anymore. But I do have another problem. How do I make a ball move to (x,y) from it initial position?

I have to make a football game where the ball is position somewhere. The user can choose how far it can go sideway and how high or low it can go in terms of height using the arrow keys on the keyboard. There is two bars that indicate how much you want the ball to go sideway and in term of height. So you will know.

Then the user enter a key on the keyboard and the ball is fired to that destination. How can I do that? I have created the scene and the ball. I used global variable for the ball x and y initial position.
 
Small question:

I was testing out an extension to add in embedded tweets to posts. The way I did this was to:

1. Grab all anchors in post divs.
2. Filter anchors by those which lead to statuses by looking at the HREF.
3. Use Twitter API to fetch formatted embed post with URL.

I noticed that sometimes this didn't work, due to some of the links being directed through Viglink. I can't use these links with the aforementioned API due to them being unrecognized - is there a way to handle this aside from stripping the Viglink part?
 
If I were to self-teach myself to become a kick-ass java programmer -- without having to buy any books -- where would I begin?

Oh silly you, there are no kick ass Java programmers!

Look at the top, good quality, open source Java utilities. Read their source code.
 
Sure, I'd love to get there, but I want to learn what all of the code and terminology means too. I'm a total newbie. Some people draw, take photos -- I want to learn how to program stuff. Doesn't have to be strictly java I guess.

Do yourself a favor and start with Python then. Much more friendly and is widely used in the industry (Youtube built using Python).

Don't worry about being good for a while, it will take a lot of time to actually get there. Just watch a lot of tutorials, question them and don't get influenced too easily. The key is to not work hard but work smart. If you ever find yourself doing something monotonous while coding you are doing something wrong.

After you got the basics down, build something on your own, a pet project. A small webpage (Django) or game (pyglet, pygame) might do the trick.
 
i'm assuming that all languages share a lot of concepts, with syntax being the major differentiator. at what point should i consider myself 'done' with python (I know this'll be a while) and move on - essentially, how do you know when you've learned the last concept?

Languages evolve over time so I don't think you are "done" with a language. You just switch to another one that better suits your needs of a particular project. Python is generally all purpose so there's little reason to switch from it.

After you scratch the surface there are deep diference in the languages that actually just make your life easier.
 

upandaway

Member
Does anyone have any tips about whether I should use Hamcrest or FEST (or even neither)? From a first look, it seems like I can just go with whatever, but I don't wanna commit to a choice that is secretly worse. (edit: to specify, I'm talking in Java)

Any help appreciated

After I'm done with JUnit in Action, I'm gonna finally pick up Python too. Can't wait to learn just how much pain I was inflicting on myself all this time.
 

Atruvius

Member
I'm having some trouble trying to validate int input in C++. The program should only continue if the user inputs a valid number, if the user inputs a number the program then loops until a valid number is given. I have tried to do this for hours in many different ways but I haven't gotten anywhere. Here's a snippet from my project where the thing should happen:

Code:
int pNumber;

while(!cin);
	{		
	cin >>pNumber;
	cin.clear();
	cin.ignore();
	if(!cin){cout <<"input a number!" << endl;}
	}

Any help would be welcome.
 

RobertM

Member
I'm having some trouble trying to validate int input in C++. The program should only continue if the user inputs a valid number, if the user inputs a number the program then loops until a valid number is given. I have tried to do this for hours in many different ways but I haven't gotten anywhere. Here's a snippet from my project where the thing should happen:

Code:
int pNumber;

while(!cin);
	{		
	cin >>pNumber;
	cin.clear();
	cin.ignore();
	if(!cin){cout <<"input a number!" << endl;}
	}

Any help would be welcome.
The first that you should do is a do...while() loop instead so you get something from the user first and then check if it's a valid character. Once the user enters carriage return(presses enter), call a function that contains an array full of numeric character which will be compared to the inputed string from the user. There are a slew of ways to go about the problem.
Another example http://stackoverflow.com/questions/10828937/how-to-make-cin-to-take-only-numbers
 

Atruvius

Member
The first that you should do is a do...while() loop instead so you get something from the user first and then check if it's a valid character. Once the user enters carriage return(presses enter), call a function that contains an array full of numeric character which will be compared to the inputed string from the user. There are a slew of ways to go about the problem.
Another example http://stackoverflow.com/questions/10828937/how-to-make-cin-to-take-only-numbers

Got it to work, thanks a bunch!
 

Jackben

bitch I'm taking calls.
C++ beginner here, trying to code a program that will calculate and output population growth info for two different regions based on user input. I think it works as far as I want it too, but the code is awfully long and unpleasant. Mostly looking for tips to help clean it up.

It takes the pop # and growth rate % and outputs how many years until the pop of the smaller will eclipse the larger and the pop of both towns at that time if applicable. If both are equal but have different rates, if they are equal with the same rates, or if the smaller region will never eclipse the other due to growth rates it also outputs a special message.

Any help is greatly appreciated.

http://pastebin.com/DQDVdyWm

Code:
#include <iostream>
#include <iomanip>
#include <string>
 
using namespace std;
 
int main()
{
 
        string townA, townB;
        int popA, popB, lead, year=0;
        double rateA=0.00, rateB=0.00;
 
        cout << "Please enter the name of the first town"
                 << " and press enter: " << endl;
 
        getline (cin, townA);
 
        cout << "\nEnter the name of the second town: " << endl;
 
        getline (cin, townB);
 
        cout << "\nEnter the population & growth rate for "
                 << townA << " separated by space." << endl;
 
        cin >> popA >> rateA;
 
        cout << "\nEnter the population & growth rate for "
                 << townB << " separated by space." << endl;
 
        cin >> popB >> rateB;
 
        if (popA == popB && rateA == rateB)
        {
                cout << "\nBoth populations match & will grow equally."
                     << endl;
            cout << townA << " Population: " << popA << " "
                     << "Growth Rate: " << rateA << "%\n"
                     << townB << "Population: " << popB << " "
                     << "Growth Rate: " << rateB << "%\n" << endl;
 
                system("Pause");
 
                return 0;
        }
 
        if (popA == popB && rateA > rateB)
        {
                cout << "\nBoth populations match, but will grow differently."
                     << endl;
                cout << townA << " Population: " << popA << " "
                     << "Growth Rate: " << rateA << "%\n"
                     << townB << " Population: " << popB << " "
                     << "Growth Rate: " << rateB << "%\n" << endl;
 
          system("Pause");
 
          return 0;
        }
 
        else if (popA == popB && rateA < rateB)
                        {
                cout << "\nBoth populations match, but will grow differently."
                     << endl;
                cout << townA << " Population: " << popA << " "
                     << "Growth Rate: " << rateA << "%\n"
                     << townB << " Population: " << popB << " "
                     << "Growth Rate: " << rateB << "%\n" << endl;
 
          system("Pause");
 
          return 0;
        }
       
        if (popB > popA && rateA == rateB)
        {
                cout << "\nAny population disparity will grow indefinitely."
                     << endl;
                cout << townA << " Population: " << popA << " "
                     << "Growth Rate: " << rateA << "%\n"
                     << townB << " Population: " << popB << " "
                     << "Growth Rate: " << rateB << "%\n" << endl;
 
          system("Pause");
 
          return 0;
        }
 
        if (popA > popB && rateA > rateB)
        {
                cout << "\nAny population disparity will grow indefinitely."
                     << endl;
                cout << townA << " Population: " << popA << " "
                     << "Growth Rate: " << rateA << "%\n"
                     << townB << " Population: " << popB << " "
                     << "Growth Rate: " << rateB << "%\n" << endl;
 
          system("Pause");
 
          return 0;
        }
 
        if (popB > popA && rateB > rateA)
        {
                cout << "\nAny population disparity will grow indefinitely."
                     << endl;
                cout << townA << " Population: " << popA << " "
                     << "Growth Rate: " << rateA << "%\n"
                     << townB << " Population: " << popB << " "
                     << "Growth Rate: " << rateB << "%\n" << endl;
 
          system("Pause");
 
          return 0;
        }
       
        if (popA > popB)
        {
                lead = 1;
        }
 
        do
        {
                popA += (popA * (rateA / 100));
                popB += (popB * (rateB / 100));
                year++;
        }
        while (popA < popB);
 
        do
        {
                popA += (popA * (rateA / 100));
                popB += (popB * (rateB / 100));
                year++;
        }
        while (popA < popB);
 
        if (lead == 1)
                {
                        cout << "\nThe population of " << townB <<
                        " will eclipse " << townA << " in: " << endl;
                        cout << year << " year(s).\n";
 
                        cout << "\nAt that time " << townA << "'s population "
                                << "will be:\n" << popA << " and "
                                << townB << "'s population: " << popB << endl;
                }
        else
        {
                cout << "\nThe population of " << townA <<
                        " will eclipse " << townB << " in: " << endl;
                cout << year << " year(s).\n";
 
                cout << "\nAt that time " << townA << "'s population "
                         << "will be:\n" << popA << " and "
                         << townB << "'s population: " << popB << endl;
        }
 
        cin.ignore(2);
 
        system("Pause");
 
        return 0;
 

nan0

Member
Identify code that you use more than once and encapsulate it into a separate method. E.g. you print in almost all cases an overview over the growth:

Code:
cout << townA << " Population: " << popA << " "
                     << "Growth Rate: " << rateA << "%\n"
                     << townB << " Population: " << popB << " "
                     << "Growth Rate: " << rateB << "%\n" << endl;

Instead of having the same code all over again, put that stuff into a method with the variables as parameters and just call that method.
 

Jokab

Member
@Jackben:

Any time you find yourself copy-pasting code you're probably doing something you shouldn't. In the code below I've extracted what statements are duplicated inside a lot of the if statements and sent the appropriate values/strings to the function that needs it. Also I've re-arranged the logic a bit in the if-statements to remove some redundancy.

Code:
#include <iostream>
#include <iomanip>
#include <string>
 
using namespace std;

void printEnterPopMessage(string town) {
    cout << "\nEnter the population & growth rate for "
         << town << " separated by space." << endl;
}

void printPopGrowth(string firstLine) {
    cout << "\n" << firstLine
         << endl;
    cout << townA << " Population: " << popA << " "
         << "Growth Rate: " << rateA << "%\n"
         << townB << "Population: " << popB << " "
         << "Growth Rate: " << rateB << "%\n" << endl;
}

void printEclipseMessage(string town1, string town2) {
    cout << "\nThe population of " << town1 <<
        " will eclipse " << town2 << " in: " << endl;
    cout << year << " year(s).\n";

    cout << "\nAt that time " << townA << "'s population "
            << "will be:\n" << popA << " and "
            << townB << "'s population: " << popB << endl;
}
 
int main()
{
    string townA, townB, largerTown == "";
    int popA, popB, year=0;
    double rateA=0.00, rateB=0.00;

    cout << "Please enter the name of the first town"
             << " and press enter: " << endl;

    getline (cin, townA);

    cout << "\nEnter the name of the second town: " << endl;

    getline (cin, townB);

    printEnterPopMessage(townA);
    cin >> popA >> rateA;

    printEnterPopMessage(townB);
    cin >> popB >> rateB;


    string message = "";
    if (popA == popB) {
        if(rateA == rateB) {
            message = "Both populations match & will grow equally.";
        } else if(rate A > rateB) {
            message = "Both populations match, but will grow differently.";
        } else if(rate A < rateB) {
            message = "Any population disparity will grow indefinitely.";
        }
        printPopGrowth(message);
    } else if(popB > popA) {
        if(rateB > rateA) {
            message = "Any population disparity will grow indefinitely.";
        } else if(rateB == rateA) {
            message = "Any population disparity will grow indefinitely.";
        }
        printPopGrowth(message);
    } else if(popA > popB && rateA > rateB) {
        message = "Any population disparity will grow indefinitely.";
        printPopGrowth(message);
    
    } else if(popA > popB) {
        largerTown = townA;

        do
        {
                popA += (popA * (rateA / 100));
                popB += (popB * (rateB / 100));
                year++;
        }
        while (popA < popB);
 
        do
        {
                popA += (popA * (rateA / 100));
                popB += (popB * (rateB / 100));
                year++;
        }
        while (popA < popB);

        if (largerTown == townA)
        {
            printEclipseMessage(townA, townB);
        }
        else
        {
            printEclipseMessage(townB, townA);
        }
    }

    cin.ignore(2);
    system("Pause");
    return 0;
}

Haven't test-ran it, nor do I program C++ (so excuse my Java indentation in the code I rewrote). Don't know why you do the do-while loop twice either so I didn't modify tht at all. Also not sure if the program flows the way you want to anymore, but I'm sure you can figure that out. If not, just ask. Anyway, the gist of it is: if you have the same code with very small disparities all over the place, extract what is the same to a function and call that function with what differs.

Disclaimer: Only been programming for a year so there are most likely better ways of doing this; this is just how I would do it off the top of my head.
 

Sharp

Member
I haven't looked at that program too carefully, but I'm pretty sure that second loop will always run exactly once. Why is it in a loop?

Also, I'm pretty sure you can find the point of intersection between the two populations as:

t = (ln (p_1) - ln (p_0)) / (ln (r_0) - ln (r_1))
 

Jackben

bitch I'm taking calls.
Thanks for the help, guys/gals. You've given me a lot to learn and I appreciate it. The reason so much if code is repeated is that I wasn't certain how to nest it and still achieve the desired result i.e.

-If Populations are equal and the rates are the same = none will ever grow apart

-If pops are equal but rates are different (I repeated this one for both a > B and B > a because I don't know how to call if there's a difference) = pops are already equal but will grow apart immediately.

-If pops are unequal but rates are equal = pops will always be disparate.

- if pops are different and rates are such that the smaller town has the chance to eclipse the larger eventually.

The reason I have the do...while loop twice is once for if town A is the smaller town and once for if town B is. I didn't quite figure out how to formulate that to one chunk of code either. Will look over the suggestions tonight, once again ty guys.
 

phoenixyz

Member
If you are learning C++ this might be a good start to use classes (for the towns).
Code:
#include <iostream>
#include <string>
#include <cstdint>
#include <cmath>

using namespace std;

class town {
public:
    string name;
    uint32_t population;
    double growth;

    town(string n, uint32_t p, double g) : name(n), population(p), growth(g) {}

    string toString() const {
        return name + ": Population " + to_string(population) + ", Growth rate " + to_string(growth) + ".";
    }
};


double calculateTime(town a, town b) {
    double p1 = a.population, p2 = b.population;
    return -log(p1/p2)/(log(a.growth/100.0 + 1.0) - log(b.growth/100.0 + 1.0));
}

int main() {
    town a("Town 1", 10000, 2.0), b("Town 2", 1000, 2.5);

    if(a.population == b.population) {
        cout << "Both populations match ";
        if(a.growth == b.growth) {
            cout << "and will grow equally";
        } else {
            cout << "but will grow differently";
        }
        cout << "." << endl << a.toString() << endl << b.toString() << endl;
        return 0;
    }

    town big = a, small = b;
    if(a.population < b.population) {
        big = b;
        small = a;
    }

    if(big.growth >= small.growth) {
        cout << small.name << " will never reach population of " << big.name << endl;
        cout << big.toString() << endl << small.toString() << endl;
    } else {
        cout << small.name << " will reach population of " << big.name << " after " << calculateTime(big, small) << " years." << endl;
        cout << big.toString() << endl << small.toString() << endl;
    }

    return 0;
}
 

Water

Member
Nearly all of Jackben's code is complex, conditional input and output. Even after cleanup, code like that is going to take a decent bit of space and will not feel very elegant; that's just the nature of user interface code. More importantly, besides running the input and output, the code does almost nothing. It boils down to a single calculation (which, when the formula is fully worked out like in phoenixyz's version, is just one line of code). There is no complexity in there that would benefit from using more advanced language features; even phoenixyz's usage of classes (actually structs, since all members are public) is kinda shoehorned in.

TL;DR: it's worth the time to read and understand Jokab's and phoenixyz's renditions of the code, but spending much further time on it is not going to be too fruitful, because the problem is too simple and/or artificial for meaningful improvements.
 

Onemic

Member
What is the point of overloaded functions? Or a better phrasing of that would be, what are some real world examples of what makes an overloaded function useful?
 

tokkun

Member
What is the point of overloaded functions? Or a better phrasing of that would be, what are some real world examples of what makes an overloaded function useful?

Code:
template <typename my_type>
my_type max(const vector<my_type>& elements) {
  assert(elements.size() > 0);
  my_type highest = *elements.begin();
  for (auto element : elements) {
    if (greater_than(element, highest)) {
      highest = element;
    }
  }
  return highest;
}

bool greater_than(const int& a, const int& b) {
  return a > b;
}

bool greater_than(const some_class& a, const some_class& b) {
  // some special code
}

// etc.
 

Onemic

Member
Code:
template <typename my_type>
my_type max(const vector<my_type>& elements) {
  assert(elements.size() > 0);
  my_type highest = *elements.begin();
  for (auto element : elements) {
    if (greater_than(element, highest)) {
      highest = element;
    }
  }
  return highest;
}

bool greater_than(const int& a, const int& b) {
  return a > b;
}

bool greater_than(const some_class& a, const some_class& b) {
  // some special code
}

// etc.

Should have also said I'm a complete beginner to C++ and programming in general. Reading that made my head hurt trying to understand it, haha.
 

tokkun

Member
Should have also said I'm a complete beginner to C++ and programming in general. Reading that made my head hurt trying to understand it, haha.

Sorry about that.

Basically the gist of it is: Overloaded functions are useful in what is called "generic" or "meta" programming in C++; what I showed in the example. The idea there is that the same code can be reused with different datatypes.

One place where overloading is even more commonly used is in constructors.

And sometimes people like to use them just so they don't have to remember two different function names. Ex:

Code:
void PrintString(const string& str) { // stuff }
void PrintString(const char* c_str) { // stuff }
 

Sharp

Member
Overloading is particularly useful in the context of operator overloading. Or terrible, depending on who you ask, but as far as I'm concerned when it comes to C++ the code clarity ship sailed long ago.

(Which reminds me that there was a language I used quite recently that had different operators for floating point and integer arithmetic. I wish I could remember what it was).
 

Onemic

Member
Sorry about that.

Basically the gist of it is: Overloaded functions are useful in what is called "generic" or "meta" programming in C++; what I showed in the example. The idea there is that the same code can be reused with different datatypes.

One place where overloading is even more commonly used is in constructors.

And sometimes people like to use them just so they don't have to remember two different function names. Ex:

Code:
void PrintString(const string& str) { // stuff }
void PrintString(const char* c_str) { // stuff }

So it's really only used for convenience purposes? The code that you posted earlier could be done just as efficiently with two differently named functions?
 

Sharp

Member
So it's really only used for convenience purposes? The code that you posted earlier could be done just as efficiently with two differently named functions?
I am fairly confident that overloaded functions get compiled out as different functions, so yes. For that matter, unless you're using virtual functions or templates, the vast majority of C++'s object oriented features can also be replaced by differently named functions. Like object oriented programming, function overloading is occasionally useful, so it's in the language. That doesn't mean you have to use it :) The most interesting use is probably in constructors and operators because there is syntactic sugar around them that you can't replicate otherwise. For example, if a function foo takes an object of a class A, and A has a constructor that accepts objects of class B, C++ will implicitly convert an object b of class B to class A if you call foo with b as its argument.

On a side note, if I were you, I wouldn't worry too much about efficiency at the moment. Not so much because I believe in "premature optimization," but because optimization is really hard for a ton of different reasons and it's not always obvious what will make the program as a whole run fastest even if you're very experienced with the architecture and compiler internals. For example, I recently spent a considerable amount of time optimizing a very small function that is called many, many times (possibly millions) by a larger function, until a point where it was provably faster than the original small function. That's a classic situation where optimization can matter and most people would expect that to result in a speedup of the larger program. But the program as a whole ran slower, because the time savings were due to the new version of the function not mutating its input, which turned out to increase the average number of mutations the larger function required. If you instead focus on abstraction and writing code that is maintainable with minimal effort on your part, you gain a much more tangible benefit, and it's much easier to predict maintainability than speed.
 

tokkun

Member
So it's really only used for convenience purposes? The code that you posted earlier could be done just as efficiently with two differently named functions?

In some cases this is true, but not in all cases. For instance, the name of a constructor can't be changed, so the only way to have multiple constructors is with overloading.

You could achieve something similar using a factory with different named functions to construct your objects, but that's not exactly the same behavior.

As for the code, I posted earlier, you could do it with different named functions, but you would have to create a separate template specialization for every type, and that would defeat the purpose of using templates to begin with.

But in general, it's mainly just done for convenience. The company I currently work at discourages the use of function overloading in its style guide, except for constructors and in templates.
 

usea

Member
So it's really only used for convenience purposes? The code that you posted earlier could be done just as efficiently with two differently named functions?
Most things in programming can be accomplished other ways and are just there for convenience.

Here's another example. When you write code, there's two sides to it. There's the author (you), and then the user or caller of the code. Sometimes that's also you, sometimes it's somebody else.

The way the code looks to the caller and the way they use it is called its API. It's like the code's user interface. You want to present an intuitive interface so it's easy to use. Overloading functions and methods is a tool to accomplish that.

Maybe you have a dot on the screen, and it has a .bounce() method. If you call bounce(), the dot will kind of bounce up and down a bit for a moment. What if you want to change how much it moves when it bounces, you could pass in an int called maxDistance. Or what if you want to adjust the speed of the bounce, or the direction?. You could pass those as arguments. Pretty soon you realize there's a lot of ways you can customize this behavior. One way of presenting that to the user of your code is to have several overloads of bounce() that each take different combinations of arguments. The person who just wants a simple bounce can call the empty one, and the person who wants a very specific kind of bounce can call whichever overload they want. You could even make a BounceOptions class that has 10 options and just pass an instance of that.
 
The person who just wants a simple bounce can call the empty one, and the person who wants a very specific kind of bounce can call whichever overload they want. You could even make a BounceOptions class that has 10 options and just pass an instance of that.

Also in your own code, it is a nice neat way to provide defaults and keep complex implementations in one place, which also plays especially nice with testing.

bounce()
{
bounce (DEFAULT_HEIGHT);
}

bounce(int height)
{
// do the magic
}
 

Salsa

Member
so my programming teacher uses a hotmail account

I should quit this class right

just wanted to learn some actionscript dammit
 

Water

Member
So it's really only used for convenience purposes? The code that you posted earlier could be done just as efficiently with two differently named functions?
Efficiently yes, readably and maintainably no. If you have written a Hello World -type program in C++, you have already used function overloading:
Code:
void main {
  std::cout << "Hello World! " << 101010 << std::endl;
}
This code calls three different operator<< functions. Without overloading you'd have to remember and use separate named functions for every different type you want to print. Not only would that be inconvenient, but the code would be less clear, which is a bad thing. The programmer's intention (print these things in this order) would be obscured. (C's printf() function instead asks you to specify types in a format string, which is obscure and sort of unsafe, and still doesn't allow you to print custom types of your own like overloading does.)
Overloading is even more important in math:
Code:
float k = 3;
vec3 position; // vector, length 3 (not a standard type)
mat3 xform, xform2; // 3x3 matrices (not a standard type)
 // formula can be written exactly the same as in a math textbook, easy to verify it's correct
vec3 final_position = xform * k * xform2 * position;
while without overloading it would be
Code:
vec3 final_position = xform.scalarMult(k).mat3mult(xform2).vec3mult(position);
or without member functions and without overloading (yuck)
Code:
vec3 final_position = mat3vec3mult(mat3mat3mult(mat3scalarMult(xform, k), xform2), position);
And note this was a very, very simple formula. The bigger ones I need in computer graphics become just awful without overloading.
 

Onemic

Member
Efficiently yes, readably and maintainably no. If you have written a Hello World -type program in C++, you have already used function overloading:

This code calls three different operator<< functions. Without overloading you'd have to remember and use separate named functions for every different type you want to print. Not only would that be inconvenient, but the code would be less clear, which is a bad thing. The programmer's intention (print these things in this order) would be obscured. (C's printf() function instead asks you to specify types in a format string, which is obscure and sort of unsafe, and still doesn't allow you to print custom types of your own like overloading does.)

Thanks for the explanation. I understand its purpose a lot better now.

In the next week or so I'm going to be studying math again for the first time in around 6 years. I was thinking about getting this textbook by michael spivak. Would this be a good intro text to someone that wasn't that good in math?(I got a calculus credit in HS, but I barely passed, mostly because I never studied or did hw for it) Or should I drop down to a precalculus textbook first? I ask because based on the ToC for the book it dedicates a rather lengthy 1st and 2nd chapter towards what seems to be the foundations to get you started on calculus before moving into the real stuff in the 3rd chapter.

Is there anyone who owns any of the editions of the book that can help verify this?

Also, this concept seems to be confusing me much more than overloading functions initially did. What is the purpose of passing arguments by reference using & at the end of the type in C++? The book I'm reading is trying to explain it, but I can't even begin to wrap my head around it as they only spend 2 pages to explain the concept with only one example that I don't really understand.
 

Slavik81

Member
so my programming teacher uses a hotmail account

I should quit this class right

just wanted to learn some actionscript dammit

I've never really understood why people look down on hotmail. To me, it's just another source that my email client syncs to. Whether it's Exchange or IMAP, if the client has the support, it's all the same in the end.

I wouldn't judge your teacher based on just that... though it's kind of odd that they don't use a school email.

Most things in programming can be accomplished other ways and are just there for convenience.
See also: Turing tarpits
 

snack

Member
What is a good site to learn Java? I would like to develop some apps on Android.

I don't mind getting some books on them too, so any recommendations on those would be amazing as well. Many thanks.
 
What is a good site to learn Java? I would like to develop some apps on Android.

I don't mind getting some books on them too, so any recommendations on those would be amazing as well. Many thanks.
Head First Java was a good dive to the language in my opinion. Not boring and made learning fun and easy to grasp. Definitely helped me jump straight into my data structures class I'm currently taking. However, it's a bit outdated but the fundamentals are still presented well. My only complaint about it is they don't they don't talk about worst case or recursion. I had to learn that on my own but it's slowly getting better. Codingbat is good for exercises as well. Most are easy but it's good to get you thinking. I bet other people here can recommend something better.

So I'm back with another question about worst case but with BST. I did well on my first midterm and hoping to continue. Usea definitely helped me with answering my question last time since there was a similar question on the exam and I got full credit. (Thank you again!)

So using my friend's past midterm, the question:
Starting with an empty BST, a sequence of n items is inserted into it, one at a time. The BST is not allowed to have any duplicate keys. What is the worst case big O running time to insert all n items?

My answer:
First observation, the worst case will be if ever node forms a single branch.
So starting with an empty BST tree, we make zero comparison and just add the node. After the root node is no longer null, we make 2 comparisons(if it's equal and greater or less than), and then insert it in it's rightful place. This will keep going for n items. 2(n-1). If we have n items, n[2(n-1)], essentially O(n^2).

Now, I looked at wiki and it says the worst case for a BST tree is O(n). Why is it O(n)?
 

smiggyRT

Member
c# Form questions.

I'm loading an xml file into a dataGridView, then want to filter the date by year when a button is clicked.

How i'm loading that xml file.
Code:
                DataSet xmlds = new DataSet();
                xmlds.ReadXml("testdemoxml.xml");

                this.dataGridView1.DataSource = xmlds.Tables[0];

snippet of the xml file
Code:
<row>
  <id>1</id>
  <description>description 1</description>
  <thedate>2013-06-12T00:00:00</thedate>
  <somenotes>some notes1asdsadsadsad</somenotes>
</row>

So yeah, google doesn't seem to be offering up a clear answer for what will end up in this...
Code:
private void yearFilterButton_Click(object sender, EventArgs e)
        {

        }
to display only items from this year.

Appreciate a nod in the right direction, hope I gave enough info :D
 
Also, this concept seems to be confusing me much more than overloading functions initially did. What is the purpose of passing arguments by reference using & at the end of the type in C++? The book I'm reading is trying to explain it, but I can't even begin to wrap my head around it as they only spend 2 pages to explain the concept with only one example that I don't really understand.

The basic difference between call by reference and call by value is twofold:
1) Memory usage
2) The source value

Call by value is when you pass a value to another function without using "&". You are making a copy of that value's data type and information. The copy is the data that is acted upon within this new function without your original value being affected. This uses more memory (since a copy is created) and your original value is not touched.

Pass by reference is when an "&" is used (I've always put it before but he said after. Maybe it's both?) with your value. This passes the address where the value is stored so the new function is affecting the original value and no copy is created. This uses less memory (again, because there is no copy) and your original value is being used.


As an example, say you're using an int called position with a value of 5. When passed, the new function adds 4 before returning it. This would be the difference:

Value: 5 ->(passed to function and 4 added)-> 9 ->(returned to function)-> 5
Reference: 5 ->(passed to function and 4 added)-> 9 ->(returned to function)-> 9
 

Onemic

Member
The basic difference between call by reference and call by value is twofold:
1) Memory usage
2) The source value

Call by value is when you pass a value to another function without using "&". You are making a copy of that value's data type and information. The copy is the data that is acted upon within this new function without your original value being affected. This uses more memory (since a copy is created) and your original value is not touched.

Pass by reference is when an "&" is used (I've always put it before but he said after. Maybe it's both?) with your value. This passes the address where the value is stored so the new function is affecting the original value and no copy is created. This uses less memory (again, because there is no copy) and your original value is being used.


As an example, say you're using an int called position with a value of 5. When passed, the new function adds 4 before returning it. This would be the difference:

Value: 5 ->(passed to function and 4 added)-> 9 ->(returned to function)-> 5
Reference: 5 ->(passed to function and 4 added)-> 9 ->(returned to function)-> 9


I'm still sorta confused. When would you use it? Is it only used in situations where you want to save memory?

Im trying to mess around with it in visual express, and I notice that you can't simply pass a value into the referenced argument. You need to define and initialize a variable that will be passed as an argument instead. the value it returns to the console when compared to the same value, but not referenced is the same.
 

phoenixyz

Member
Im trying to mess around with it in visual express, and I notice that you can't simply pass a value into the referenced argument.
A reference has to be declared as const, otherwise you won't be able to pass a literal to it (as you would be able to change that literal via the reference).
 
I'm still sorta confused. When would you use it? Is it only used in situations where you want to save memory?

Im trying to mess around with it in visual express, and I notice that you can't simply pass a value into the referenced argument. You need to define and initialize a variable that will be passed as an argument instead. the value it returns to the console when compared to the same value, but not referenced is the same.

Consider this block of code:
Code:
#include <iostream>

using namespace std;


void addition( int position )
{
        position += 4;

        cout << position << endl;
}

int main( void )
{
        int position = 5;

        addition( position );

        cout << position << endl;

        return 0;
}
Output:
Code:
9
5
This is call by value. Position appears to be passed to the function addition. However, in reality a copy of position is being made and used in addition. Now I named the new int position in the addition function but you could name it bobbyJoe or dillyBar and it would still work. Although position is being passed in, it needs to have a place to go. If there is not an variable for it to be placed in then your compiler will throw an error. Call by value can be used if you are trying to determine a calculation based on information you currently have but want to be assured it won't be messed with. Say position is an x value in your function. You don't want x to accidentally be changed because of a bug in your function. That's a logic error and those are the worst to fix.

Now consider this code:
Code:
#include <iostream>

using namespace std;


void addition( int *position )
{
        *position += 4;

        cout << *position << endl;
}

int main( void )
{
        int position = 5;

        addition( &position );

        cout << position << endl;

        return 0;
}
Output:
Code:
9
9
This is call by reference. If you don't know what the stars are for that's called pointers and I'm not about to explain that right now (not important for this demonstration anyways). In this example, position's address is being passed to addition (hence the ampersand). When printed out, both answers should be the exact same because you've changed the value within position's address rather than changed the value of a copy of position. Call by reference is useful for many, many things. Say you have information within your main function that needs to be modified, created or destroyed by other functions. Passing by reference allows you to do this and keep your functions smaller (hopefully, more readable).

Hope that was even remotely useful. Others here are more knowledgeable than me, however, and can chime in where I've gone wrong.
 

usea

Member
c# Form questions.

I'm loading an xml file into a dataGridView, then want to filter the date by year when a button is clicked.

How i'm loading that xml file.
Code:
                DataSet xmlds = new DataSet();
                xmlds.ReadXml("testdemoxml.xml");

                this.dataGridView1.DataSource = xmlds.Tables[0];

snippet of the xml file
Code:
<row>
  <id>1</id>
  <description>description 1</description>
  <thedate>2013-06-12T00:00:00</thedate>
  <somenotes>some notes1asdsadsadsad</somenotes>
</row>

So yeah, google doesn't seem to be offering up a clear answer for what will end up in this...
Code:
private void yearFilterButton_Click(object sender, EventArgs e)
        {

        }
to display only items from this year.

Appreciate a nod in the right direction, hope I gave enough info :D
In .NET, the type for messing with dates is called DateTime. You can make a DateTime from your string "2013-06-12T00:00:00" using DateTime.Parse(). You can either put the DateTimes in your DataGrid instead of strings, or you can create them just for filtering. Either way, they have a lot of methods and properties that are useful. For example, there's a property .Year which refers to just the year. It returns an int.

As a simple example, say you have just a list of dates as strings in the format you posted. Here's one way you could get only the dates that are in this year:
Code:
public IEnumerable<DateTime> FilterDatesByYear(IEnumerable<string> dateStrings)
{
    //this list will hold our DateTime objects we've converted from strings
    var dates = new List<DateTime>();
    
    foreach(var dateString in dateStrings)
    {
        var date = DateTime.Parse(dateString); //parse the string to a DateTime
        dates.Add(date);
    }
    
    //DateTime.Now gives you a DateTime for this moment in time. .Year is the year of that date (this year)
    var thisYear = DateTime.Now.Year;
    
    //this will hold only the DateTimes that fall in this year)
    var datesThisYear = new List<DateTime>();
    foreach(var date in dates)
    {
        if(date.Year == thisYear)
        {
            datesThisYear.Add(date);
        }
    }
    return datesThisYear;
}

Here's another way, which does basically the same thing:
Code:
public IEnumerable<DateTime> FilterDatesByYear(IEnumerable<string> dateStrings)
{
    return dateStrings.Select(x => DateTime.Parse(x)).Where(x => x.Year == DateTime.Now.Year);
}

Here's an example of it being used:
Code:
FilterDatesByYear(new[]{"2013-06-12T00:00:00", "2012-04-19T00:00:00", "1999-01-11T00:00:00", "2013-09-20T00:00:00"})
This will return only the two dates in 2013.

I don't know exactly what you want to do when the yearFilterButton is clicked, but you can use the code above to at least get the dates from this year.
 

smiggyRT

Member
I don't know exactly what you want to do when the yearFilterButton is clicked, but you can use the code above to at least get the dates from this year.

So basically I have this

JRTmxPK.png


And the idea is you choose the filter button at the top and the grid is repopulated with rows containing dates only from this year.

Thanks for the help with parsing the dates, I was certainly clueless on that. The problem I see now is how to filter out the rows that down contain the dates from his year. Struggling to figure out where to even start on that part and my googling skills aren't up to scratch apparently.

The documentation petriP linked to for datagrid went way over my head and didn't seem to apply to datagridview? Yeah, I'm lost :/
 

tokkun

Member
I'm still sorta confused. When would you use it? Is it only used in situations where you want to save memory?

Im trying to mess around with it in visual express, and I notice that you can't simply pass a value into the referenced argument. You need to define and initialize a variable that will be passed as an argument instead. the value it returns to the console when compared to the same value, but not referenced is the same.

You can pass a "value" (better to say 'literal value' or 'literal') to a function that takes a reference as an argument, however it must be a const reference.

Code:
void my_function(const int& arg) {
// stuff
}

void my_function2(int& arg) {
// stuff
}

void some_other_method() {
  // ...
  my_function(0); // OK
  my_function2(0); // Compilation error
}

The reason that it must be a const reference is because non-const references can be assigned to, however it is illegal to try to assign a different value to a literal.

Code:
void assign6(int& my_val) {
  my_val = 6;
}

int main (...) {
  ...
  int a = 3;
  assign6(a);  // Legal. Now a = 6.
  assign6(3);  // Illegal. 3 = 6? Doesn't make sense.
}

To explain the larger question of passing by value vs references (or pointer) consider this analogy:

Passing by reference (or pointer) is like giving you the address to my house.
Passing by value is like constructing an exact duplicate of my house next door to you.

-It is going to be more expensive to give you a copy of my house (assuming my house is not just something simple like a paper cutout), because there needs to be land for the new house, and everything needs to get rebuilt.

-If I give you the address to my house, you can show up and smash my TV with a baseball bat, and it will affect me. However if you smash the TV in the duplicate house, I will never know.

-Conversely, if I decide to burn down my house for the insurance money, if I gave you the address, it will be gone for you, but if I made the duplicate, it will still be there.

Those are the main things to consider when deciding to pass something by value or by reference:
1. Is it a large, complex thing that will be expensive to copy?
2. Do I want any changes the function makes to be visible to the caller?
3. Can the function trust the caller not to destroy the object before the function is done using it? (this is important for multi-threaded programming)

Is it something other than a simple type (int, double, char, etc.): Favor passing reference
Do you want the caller to see your changes: Favor passing reference
Are you are worried about the lifetime of the object: Favor passing by value or passing by reference and making a local copy.

You can also substitute "pointer" for "reference" in these examples, with the main difference being whether you want to allow null pointers to be passed.
 
Top Bottom