Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
TasteMyHouse
Dec 21, 2006
you can just use a valarray.

Adbot
ADBOT LOVES YOU

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

pseudorandom name posted:

The question is, of course, was that worth the effort?
Well I appreciate the effort you went to to show a comical application of complex operations as applied to a simple task, making the simple task slower, longer, more work and more complicated than the problem warrants. So for me, yes, it was worth the effort, thanks!

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.

shrughes posted:

Edit: Also, no there's no native way. Unless the arrays are declared with a fixed size.
What are you talking about?

intruder13
Jun 25, 2004
Intruder alert!
What OS/IDE combo is best for installing libraries? (Ideally, using a package system like in Linux). Is there a general guide to installing libraries and working with .dll and .lib files? (I use Visual C++ 2010).

I am confused each time I start a new project with Allegro, boost or SFML, having to set it up again even though I might have gotten it to work before.

raminasi
Jan 25, 2005

a last drink with no ice
I'm pretty sure you can create your own project templates so you can just click "Create a new boost project" or whatever and have all the settings correctly configured.

intruder13
Jun 25, 2004
Intruder alert!
I can't find where that is. I have the express version of Visual Studio if that matters.

nielsm
Jun 1, 2009



intruder13 posted:

What OS/IDE combo is best for installing libraries? (Ideally, using a package system like in Linux). Is there a general guide to installing libraries and working with .dll and .lib files? (I use Visual C++ 2010).

I am confused each time I start a new project with Allegro, boost or SFML, having to set it up again even though I might have gotten it to work before.

Create some Property Sheets that covers your things, then you can just add one of those to a project to get all the settings. E.g. create one that adds the Allegro include dirs, library dirs and any other compiler settings it needs.

If you do as GrumpyDoctor suggests, you can still also use property sheets (to keep the project file cleaner), but you get the advantage of having some template code files generated as well. Of course, you have to create those first :)

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

nielsm posted:

Create some Property Sheets that covers your things, then you can just add one of those to a project to get all the settings. E.g. create one that adds the Allegro include dirs, library dirs and any other compiler settings it needs.
Man, that would have been helpful to me a few months ago. I found Express didn't let you make templates, didn't find anything that worked as an alternative, so I ended up just making a perl script to clone my 'template' project, replacing a number of placeholders with the value given to the script on the command line.

On the up side, my script does a little more for me than property sheets likely would, but on the down side, property sheets would presumably mean if I want to change something I could change it across all the shared-attribute projects rather than one at a time. (I was doing this for making many similar plugins.)

Good Will Punting
Aug 30, 2009

And as the curtain falls
Just know you did it all except lift weights
code:
void main(){

	infile.open("input1.dat");
	infile.get(num);

	while(!infile.eof()){
		if(isalnum(num)){
		count_one++;
		infile.get(num);
		}
	}

	infile.close();
	infile.open("input1.dat"); //reset the infile after initial read

	for(int i=0; i < count_one; i++){
		infile.get(num);
		a[i] = num - '0';
		cout << a[i];
	}

	infile.close();

	infile2.open("input2.dat");
	infile2.get(num2);

	while(!infile2.eof()){
		if(isalnum(num2)){
		count_two++;
		infile2.get(num2);
		}
	}

	cout << count_two;

	infile2.close();
	infile2.open("input2.dat"); //reset the infile after initial read

	for(int j=0; j < count_two; j++){
		infile2.get(num2);
		b[j] = num2 - '0';
		cout << b[j];
	}
}
The first part, using infile and input1.dat, works fine. It reads in input1.dat and prints out the contents of a[]. For some reason, the second part won't work. "cout << count_two" doesn't display anything. Am I missing something with the way file input is done? (Answer: Probably).

nielsm
Jun 1, 2009



Well, if your input files don't contain all alphanumerics, in whatever form, you're getting some nice infinite loops.

Try indenting your code properly:
code:
	while(!infile.eof()){
		if(isalnum(num)){
			count_one++;
			infile.get(num);
		}
	}
Note that you only read the next item if the current item succeeded the isalnum() test, otherwise the current item is kept and tested once more, and the file is never read from again. It just keeps testing the same value over and over again, until you abort the program, or cosmic radiation flips a lucky bit.

Good Will Punting
Aug 30, 2009

And as the curtain falls
Just know you did it all except lift weights
Right. They're both .dat files with one string of numbers, no spaces, nothing else. No idea why the first portion works and the second doesn't. When I run my program, it doesn't exit. After printing the contents of input1.dat, it stays in limbo for a while.

Good Will Punting fucked around with this message at 18:01 on Aug 21, 2011

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Good Will Punting posted:

Right. They're both .dat files with one string of numbers, no spaces, nothing else. No idea why the first portion works and the second doesn't. When I run my program, it doesn't exit. After printing the contents of input1.dat, it stays in limbo for a while.
A newline at the end of the numbers would cause the infinite loop freeze - are you absolutely certain there's nothing else?

As nielsm implies, it looks like your code would easily accommodate skipping over newlines, spaces, whatever, if you just moved the 'get' outside of the 'if' (though then you'd get a horrible error because you only do the isalnum condition for counting, not for the actual reading - another alternative then, if you don't want to fix that problem properly, would be to put an 'else' on that 'if' where the 'else' outputs "your data file has poo poo in it" and exits. Edit: or the 'else' could just break from the loop, that way anything after the first non-digit wouldn't be read on the second pass.)

The most useful and more general advice for your situation is that now would be a good time to learn to use the debugger. Probably gdb if you're operating in a Unix-like environment, or the "start debugging" option in Visual Studio, or whatever equivalent option your IDE has. That way you can step through the code and find where it's getting stuck in a loop, and see, from the variables, the reason why.

roomforthetuna fucked around with this message at 18:16 on Aug 21, 2011

Good Will Punting
Aug 30, 2009

And as the curtain falls
Just know you did it all except lift weights
Checked it over once more, ran the debugger. The error was weird so I Googled it and it told me to rerun VS2010 as an Admin, which I could swear I had set to default, but worth a shot right? Sure enough, the box was unchecked! Things are just dandy now, except that I'm thoroughly confused as to why this happened. Last time I had an admin issue, I set it to default to Run as Admin. It appears to have reverted back.

Oh well thanks! Also, sorry for being a pest! (School has been a terrible way to learn C++ thusfar).

Paniolo
Oct 9, 2007

Heads will roll.
Has school ever taught anyone C++ well? My own experiences with learning C++ in school is that it's taught as "C with classes" and topics like templates, STL (outside of cin/cout and maybe std::string), references, smart pointers, RAII, exceptions, etc. aren't even mentioned. It seems to me it would be less harmful to not teach C++ at all.

I remember one professor asking me why in the world I had an overloaded assignment operator returning a self-reference in a homework assignment. He simply couldn't understand why anyone would do that.

TasteMyHouse
Dec 21, 2006

Paniolo posted:

Has school ever taught anyone C++ well? My own experiences with learning C++ in school is that it's taught as "C with classes" and topics like templates, STL (outside of cin/cout and maybe std::string), references, smart pointers, RAII, exceptions, etc. aren't even mentioned. It seems to me it would be less harmful to not teach C++ at all.

I learned templates, classes, the dangers of "dumb" pointers and bare arrays, intro to the stl (std::vector, std::deque and some others), and operator overloading in college. The dude even briefly talked about virtual functions though I'm pretty sure it went over everyone's heads. He'd been an actual professional software engineer, unlike most other professors I've had.

Good Will Punting
Aug 30, 2009

And as the curtain falls
Just know you did it all except lift weights
This is the 2nd time I've taken a C++ course and it covers a lot of material, which is good, but it's going too quickly and we don't have enough practice implementing stuff. We've covered a shitton in lectures and notes, but as far as actually putting it into practice, we get asked to combine all this poo poo at once, in a few extremely difficult projects and two tests (which are a large chunk of our grade each) and it's overwhelming.

Of what you've mentioned, we have covered overloaded operators, references, some pointers, templates, and portions of the STL (and obviously the usual class stuff). We're now doing vectors and recursion. However, while I understand it in theory, putting it all together has been a challenge for me, something things near impossible.

It wouldn't be an issue if my grade was based on projects (because those help me learn so far), but they count for 0% and the tests are 100%. It's really difficult to do well on a 3 hour test when this is the first time you've worked with C++ and you're asked to use all these concepts with minimal practice beyond one example.

Good Will Punting fucked around with this message at 20:40 on Aug 21, 2011

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Paniolo posted:

Has school ever taught anyone C++ well? My own experiences with learning C++ in school is that it's taught as "C with classes" and topics like templates, STL (outside of cin/cout and maybe std::string), references, smart pointers, RAII, exceptions, etc. aren't even mentioned. It seems to me it would be less harmful to not teach C++ at all.
Your experiences match mine. I only recently started using STL templates after about 8 years of using "C++" without bothering, and wow it makes life a lot easier (though also sometimes really frustrating because the error messages are godawful, especially const-related things.) Especially STL lists/deques/vectors/sets/maps make using appropriate data structures so much easier.

Ironically, the one STL thing I don't make much use of is streams, the one thing that was taught at my university. But that's because I do a lot of async, overlapped and binary IO which the STL stuff (as far as I can tell) isn't great for.

Edit: they did 'cover' references, it was just largely pointless (ha ha) as it was essentially "it's like a pointer that you can't change and which is more confusing." (Okay, they claimed it was less confusing so as to excuse their existence, but that's bullshit, they are way more confusing if you understand pointers.) No mention of lvalues or other actually useful uses.

roomforthetuna fucked around with this message at 23:09 on Aug 21, 2011

Good Will Punting
Aug 30, 2009

And as the curtain falls
Just know you did it all except lift weights
Just curious: Were you guys tested or did your courses grade you mostly based on projects? I'm stressing out because I can't figure these problems out quickly enough and I feel like it will cripple me for my test. I understand the concepts and can work everything out if I do it slowly, but god drat when I start to rush my brain gets overloaded. Sadly, that's the only way I'll succeed.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed

roomforthetuna posted:

Ironically, the one STL thing I don't make much use of is streams, the one thing that was taught at my university. But that's because I do a lot of async, overlapped and binary IO which the STL stuff (as far as I can tell) isn't great for.
Streams aren't great for anything. There's a bunch of nifty ideas behind streams, and occasionally they seem nice when you can write one-liners like copy(istream_iterator<int>(file), istream_iterator<int>(), back_inserter(vec)); to read a list of ints from a file, but most of the time they're just a giant overcomplicated mess that solve all the wrong problems.

intruder13
Jun 25, 2004
Intruder alert!

nielsm posted:

Create some Property Sheets that covers your things, then you can just add one of those to a project to get all the settings. E.g. create one that adds the Allegro include dirs, library dirs and any other compiler settings it needs.

Property sheets broke VS 2010, I think (I must have did something wrong); now it won't make new projects. I tried the reset settings but it didn't work. Also, reinstalling didn't work.

raminasi
Jan 25, 2005

a last drink with no ice
Did you nuke all the VS-looking folders you could find in AppData?

intruder13
Jun 25, 2004
Intruder alert!

GrumpyDoctor posted:

Did you nuke all the VS-looking folders you could find in AppData?

I think I deleted a few. I will check again.

Fixed. Didn't delete enough apparently.

intruder13 fucked around with this message at 00:05 on Aug 22, 2011

Polio Vax Scene
Apr 5, 2009



Hey all, I just started learning how to do stuff in C++ yesterday, and I've run into a bit of a stupid problem.

First of all, you'll need my messy code.

As you can see, I have a class obj, which has some fancy linking going on; I've also got a function obj_create(). Right now obj_create() is always returning 1. What I want to do is change it so that obj_create() returns a pointer to the obj that was just created...but every time I try a different way to wrestle that in the compiler just goes absolutely nuts.

I appreciate any advice, and also criticism on anything I'm doing that will bite me in the future; best to catch things while I'm still learning.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Well first of all you should actually indent stuff.

This is terrible:
code:
if (head2!=0) {
while (head2->next!=0)
{head2=head2->next;}
obj *newobj = new obj(a,b,type);
newobj->next=0;
newobj->prev=head2;
head2->next=newobj;
return 1;
} 
else {
obj *newobj = new obj(a,b,type);
newobj->next=0;
newobj->prev=0;
head=newobj;
return 1;
}
I mean look at it. You can't make head nor tail of how control flows through that mess, or anything else. The whole point of structured programming is to give stuff structure.

Like this:
code:
if (head2!=0) {
   while (head2->next!=0)
      head2=head2->next;

   obj *newobj = new obj(a,b,type);
   newobj->next=0;
   newobj->prev=head2;
   head2->next=newobj;
   return 1;

} else {
   obj *newobj = new obj(a,b,type);
   newobj->next=0;
   newobj->prev=0;
   head=newobj;
   return 1;
}
The code is semantically identical. But the structure is much more apparent.

Secondly, why do you even need an obj_create? Why isn't the obj constructor sufficient?

Jabor fucked around with this message at 09:08 on Aug 22, 2011

nielsm
Jun 1, 2009



After indenting your code, consider why you are building a makeshift linked list of your objects, instead of using one of C++'s standard container templates.

code:
#include <list>

std::list<obj> objects;

int main()
{
  // ... initialisation etc

        else if (ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN) {
          switch (ev.mouse.button) {
          case 1:
            key[MOUSE_LEFT]=true;
            grid_x=floor((float) ev.mouse.x/16)*16;
            grid_y=floor((float) ev.mouse.y/16)*16;

            // Construct a new obj and add to the end of the 'objects' list
            objects.push_back(obj(grid_x,grid_y,1));
            // now get a reference to the last object, i.e. the new one
            obj &your_new_object = objects.last();
            // that reference isn't actually used for anything here, but
            // now you have one if you want it

            break;

  // ... more code
}

// scrap obj_create, you don't need it
This makes your objects live directly in the list and be owned by it, which can save you some memory management headaches.

Gerblyn
Apr 4, 2007

"TO BATTLE!"
Fun Shoe

Manslaughter posted:

Hey all, I just started learning how to do stuff in C++ yesterday, and I've run into a bit of a stupid problem.

First of all, you'll need my messy code.

As you can see, I have a class obj, which has some fancy linking going on; I've also got a function obj_create(). Right now obj_create() is always returning 1. What I want to do is change it so that obj_create() returns a pointer to the obj that was just created...but every time I try a different way to wrestle that in the compiler just goes absolutely nuts.

I appreciate any advice, and also criticism on anything I'm doing that will bite me in the future; best to catch things while I'm still learning.

Given the complexity of what else you've already written, I'm kind of surprised you're having such an issue with your obj_create function...

Does something like this not work?

code:
obj* obj_create(int a, int b, int type)
{
   // blah blah
   obj *newobj = new obj(a,b,type);

   // blah blah

   return newobj;
}
As for other comments on your general style:

1) Avoid variable names in classes that are single letters or weird abbreviations, things like x,y,w and h may be easier to type, but x_position, y_position, width and height are much easier to read and understand.

2) If adding something to a linked list, it's much simpler to add something to the beginning than the end:

code:
if (head)
{
   newobj->next=head;
   head->prev=newobj;
   head=newobj;
}
3) If you want to learn how things like linked lists work, then there's nothing wrong with writing your own the way you're doing, but like nielsm just posted, learning to use STL types will save you a lot of time and hassle. The official documentation for the STL linked list is here:

http://www.sgi.com/tech/stl/List.html

4) You may want to use naming conventions to make your code easier to read. There are many different types and styles, but the general purpose of them is to add clues to the names of things so you can easily see what kind of thing they are. For example, many coders will put an "m" in front of the names of variables that are members of classes (e.g. "x_position" becomes "m_x_position") and "g" in front of globals (e.g. "head" becomes "g_head"). One common type (as used by Microsoft in their code) is Hungarian notation:

http://en.wikipedia.org/wiki/Hungarian_notation

Many coders (myself included) find it excessive and fiddly, and use various simplified versions, but you should be able to see the idea from the wiki page.

5) Avoid using global variables if you can, they make it harder to reuse your code and encourage you to write messy code. It's hard to explain how best to do this without writing a huge block of text, but one idea would be to make an object manager class and make things like the linked list head, object count and object creation functions members of it. This way, if for some reason you need 2 lists of objects, you can just create two instances of the manager.

Dren
Jan 5, 2001

Pillbug

Plorkyeran posted:

Streams aren't great for anything. There's a bunch of nifty ideas behind streams, and occasionally they seem nice when you can write one-liners like copy(istream_iterator<int>(file), istream_iterator<int>(), back_inserter(vec)); to read a list of ints from a file, but most of the time they're just a giant overcomplicated mess that solve all the wrong problems.

I completely agree with you. I got deep into streams one time even going so far as to implement my own streambuffers. Later, I realized that streams are nothing but a whole lot of trouble. Printf syntax, especially when spruced up like in boost or python, is absolutely the way to go when you need to output stuff.

Here's a question for boost people. I recently reverse engineered some boost binary serialized c++ objects in a hex editor and wrote some python to read in the objects. I did this for a debug tool, otherwise I wouldn't have done it at all. The python interpretation of the serialized objects is correct. Is there a better way go from boost serialized objects to python (I would rather not use Boost.Python but I have a feeling it is the more robust answer)? Does anyone have a feeling for how fragile this solution is?

raminasi
Jan 25, 2005

a last drink with no ice
code:
struct Foo {
    Foo * other_foo;
    Foo() : other_foo(this) { }
};
Is this ok? MSVS emits a warning, and I can see how it could be a problem if that initializer were doing something more complicated than just storing a pointer, but in this simple case I can't see how anything could break.

(Bonus question: if this works, will it still work if other_foo is a smart pointer?)

Paniolo
Oct 9, 2007

Heads will roll.
It'll work but it's still a bad idea.

Good Will Punting
Aug 30, 2009

And as the curtain falls
Just know you did it all except lift weights
in_1 is an input file stream

code:
while (in_1 >> ws && !in_1.eof() ){
             in_1 >> str;
Not really sure how the first expression in the while loop condition or the contents of the loop work. I was under the impression that in_1 >> ws means "read until a white space is encountered". So does the "in_1 >> str" mean "store everything read up until that white space into str"?

I should just pay one of you to be my personal C++ question answerer as I attempt (futilely) to study for my exam this weekend. There's so much little poo poo (techniques/syntax) my professor tosses into his solutions of things that he never mentions in lecture notes. And boy, Google sure is useless. This is the only useful information I've found.

Good Will Punting fucked around with this message at 02:00 on Aug 23, 2011

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
If you're confused about something, the best thing to do is actually write some code and play around with it to figure out how it works.

So start by modifying the loop a little:

code:
while (in_1 >> ws && !in_1.eof() ){
             in_1 >> str;
             cout << "ws=" << ws << ", str=" << str << endl;
Run that, see what happens.

Good Will Punting
Aug 30, 2009

And as the curtain falls
Just know you did it all except lift weights
Awesome, it does as I supposed. Wish I had known about this for my prior assignment, would have saved me some time instead of counting each white space then determining how many words there were from that.

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Paniolo posted:

It'll work but it's still a bad idea.
Why is it a bad idea? I mean, aside from putting a 'this' pointer into a thing named 'other_thing'.

More specifically, why is initializing a child object with 'this' during the constructor a bad idea, and why does it warrant a warning?

I'm thinking for something like:
code:
class TREE;

class LEAF {
public:
  TREE* Parent;
  LEAF(TREE*p) : Parent(p) {}
};

class TREE {
public:
  LEAF Child1;
  LEAF Child2;
  TREE() : Child1(this),Child2(this) {}
};
It's certainly convenient for initializing a tree type structure like that; what's bad about it?

Paniolo
Oct 9, 2007

Heads will roll.
Because at that point "this" points to an object which is not yet fully constructed, so accessing it in any way is undefined behavior.

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Paniolo posted:

Because at that point "this" points to an object which is not yet fully constructed, so accessing it in any way is undefined behavior.
Ah, so it's a bad idea because of the possibility that at some point later you might decide that (using the same example), while initializing a LEAF, you want to do something with its siblings so you go SiblingHat=Parent->Child2.Hat (or whatever) and it all goes horribly wrong because Child2 isn't initialized yet.

But if you're just initializing a pointer and you know perfectly well that you aren't going to use it for anything until after the constructor is complete, then it's really not a problem other than that "you might do something dumb later" effect. (You're not "accessing it in any way".)

Paniolo
Oct 9, 2007

Heads will roll.

roomforthetuna posted:

Ah, so it's a bad idea because of the possibility that at some point later you might decide that (using the same example), while initializing a LEAF, you want to do something with its siblings so you go SiblingHat=Parent->Child2.Hat (or whatever) and it all goes horribly wrong because Child2 isn't initialized yet.

But if you're just initializing a pointer and you know perfectly well that you aren't going to use it for anything until after the constructor is complete, then it's really not a problem other than that "you might do something dumb later" effect. (You're not "accessing it in any way".)

Yeah, that's why it's a warning not an error. It's still a bad idea though, because if you're just initializing a POD class member then why not do it in the constructor body instead, and if it's not a POD member then you're calling code with an invalid pointer as a parameter, so at any time that code could change and then you end up with REALLY hard to trace bugs.

If you have a class member which needs to take a pointer to the owning class as a parameter to its constructor and you don't want to allocate it dynamically you can use boost::optional to construct it in-place later.

The1ManMoshPit
Apr 17, 2005

It's also a bad idea because consider what happens when you do this:

code:
class Tree
{
public:
    Tree() : Child1(this), Child2(this) {}
    virtual void InitLeaf(Leaf* l) {}
};

class CoolTree
{
public:
    virtual void InitLeaf(Leaf* l)
    {
        DoSomethingCool();
    }
};

class Leaf
{
public:
    Leaf(Tree* p)
    {
         p->InitLeaf(this);
    }
};
Hint: what happens isn't good, even if you move the initialize step into the body of the constructor.

nielsm
Jun 1, 2009



The1ManMoshPit posted:

Hint: what happens isn't good, even if you move the initialize step into the body of the constructor.

It's even more fun when your base class has pure virtual methods. Calling those generally causes your program to die.
I fell into that trap recently.

The1ManMoshPit
Apr 17, 2005

One of my favourite runtime errors is "Pure Virtual Function Call."

Honestly, that's the better case, because your program crashes and blows up instead of just silently failing in weird and wonderful ways.

Adbot
ADBOT LOVES YOU

Red_Fred
Oct 21, 2010


Fallen Rib

Good Will Punting posted:

Awesome, it does as I supposed. Wish I had known about this for my prior assignment, would have saved me some time instead of counting each white space then determining how many words there were from that.

I recommend you check out https://stackoverflow.com for assignment help. They have helped me hugely.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply