So anyways this is part of some source code I found on SFML which I'm modifying/playing around with for my learning purposes. There's two lines of code in this class's destructor I don't quite understand - I've highlighted these:
[code]Space::~Space()
{
for (std::vector<Particle *>::iterator it = particles.begin();
it != particles.end(); ++it)
{
[highlight]Particle *p = *it;[/highlight]
particles.erase(it);
[highlight]delete p;[/highlight]
}
}[/code]
I understand that each pointer in the vector is being deleted in order to free up memory. However I don't get why pointer, [highlight]Particle* p[/highlight], is being assigned to every dereferenced pointer in the vector (first highlighted line), and then p being deleted (second highlighted line).
Does these two lines of code serve a purpose?
[QUOTE=thf;31331017]Okay, so I've read the entire K&R book of C[/QUOTE]
[cpp]
int
main(argc,argv)
int argc;
char** argv;
{
printf("hello world");
}
[/cpp]
??
[QUOTE=Richy19;31337650]I fail to see why you need a random for X and a nother one for Y[/QUOTE]
[QUOTE=Wyzard;31339243]Why not just make [i]one[/i] Random object and generate two numbers from it? You don't need separate RNGs for X and Y.[/QUOTE]
Yeah, I realized that after a while yesterday. It's changed now :)
[QUOTE=Map in a box;31340708]I'm trying out C, and why won't this compile?
[code]
#define test #include<stdio.h>\
int main(){\
printf("i like turtles");\
return 0;\
}
[/code][/QUOTE]
I was trying this myself a while ago when trying to write a one line program. The problem with having a multi line macro like this is that the preprocesser reads it as
[code]#include<stdio.h>\[/code] which i suspect wont compile
[QUOTE=Chrispy_645;31342226][code]Space::~Space()
{
for (std::vector<Particle *>::iterator it = particles.begin();
it != particles.end(); ++it)
{
[highlight]Particle *p = *it;[/highlight]
particles.erase(it);
[highlight]delete p;[/highlight]
}
}[/code]
I understand that each pointer in the vector is being deleted in order to free up memory. However I don't get why pointer, [highlight]Particle* p[/highlight], is being assigned to every dereferenced pointer in the vector (first highlighted line), and then p being deleted (second highlighted line).[/QUOTE]
That first highlighted line is actually dereferencing an [url=http://www.cplusplus.com/reference/std/iterator/]iterator[/url], which is acts like a pointer in some ways but it isn't necessarily an actual pointer.
Anyway, the point of this code is do delete all the pointers that are stored in the vector. It iterates over the vector so that each time through, the iterator refers to one of the stored pointers. It dereferences the iterator to get the actual stored pointer, then calls delete on the pointer to free the Particle it points to.
The [code]particles.erase(it);[/code] is wrong in this case. Erasing an element from a vector makes the vector shift all the following items down to fill the gap. With the iterator moving forward one step each time through the loop, and all the remaining items moving [i]backward[/i] one step each time due to the erasures, it'll end up skipping every other item.
The intention was clearly to discard the pointers themselves in addition to the particles they point to, but doing it one-at-a-time like that is inefficient (even if it were implemented correctly) because each time one is erased, the vector has to spend time shifting all the remaining items down to their new positions, even though those remaining items are just going to be erased themselves in later iterations. It'd be much more efficient to just put a single [code]particles.clear();[/code] [i]after[/i] the loop. But in this case even that's not necessary, because the vector's own destructor will do it automatically at the end of the Space destructor.
Can anyone see anything wrong with this?
[url]http://pastebin.com/DBTYjVum[/url]
the frag shader:
[cpp]void main(){
gl_FragColor = vec4(1,0,0,1);
}[/cpp]
And the vert shader
[cpp]attribute vec3 Position;
void main(){
gl_Position.xyz = Position;
}[/cpp]
What I get when running the program:
[thumb]http://i.imgur.com/k1i1H.png[/thumb]
What chris220 gets:
[thumb]http://i.imgur.com/861qE.png[/thumb]
The only difference between the 2 is the hardware, he has a better graphics card.
But the program is forced to use openGL 2.1 anyway so they should behave the same
[QUOTE=tagnara]...[/QUOTE]
Nope, the second edition which follows ANSI C.
[QUOTE=esalaka]...[/QUOTE]
Well, basically that's the problem. I have learnt stuff about C before and I thought I'd refresh my skills a bit by reading the book. Then I thought I'd maybe learn C++ since learning it after learning C is basically just learning some extra stuff. I [i]have[/i] read the entire tutorial of cplusplus.com and I'm not sure where to go next. I want to try out SFML eventually, but it feels like there's more stuff to learn in the C++ language, like how to properly use the STL. My problem is where I should read about that, and when I should start getting into SFML.
Oh and for some reason the reply button didn't work so I made my own quotes.
[QUOTE=thf;31345718]Then I thought I'd maybe learn C++ since learning it after learning C is basically just learning some extra stuff.[/QUOTE]
No, no, nooooo no.
C++ is programmed in a completely different manner. STL, templates, standard library, most everything is different. You can't just use it like it's C with classes.
-snip-
Not really; the SGI STL predates the standard. cplusplus.com has its own reference material for that stuff.
[QUOTE=Wyzard;31345904]Not really; the SGI STL predates the standard. cplusplus.com has its own reference material for that stuff.[/QUOTE]
Yeah, well I've seen that, but I'm not sure where to start looking in the reference.
Please don't bring your C habits into C++. Thank you.
[QUOTE=robmaister12;31341530]ah, ok. Well you should add one line that consists of "test" so that the preprocessor can go and replace it with the macro.[/QUOTE]
I did, I just removed it from there.
I'm bad with vectors and I need help.
I know the rotation of an entity. How can I get the vector that points to the direction the entity is pointing?
This is all 2D.
To get a normalized direction vector:
x = cos( ang )
y = sin( ang )
[QUOTE=Overv;31348478]To get a normalized direction vector:
x = cos( ang )
y = sin( ang )[/QUOTE]
Have us do OpenGL challenges to get open.gl release faster! PLEASE!
[QUOTE=Overv;31348478]To get a normalized direction vector:
x = cos( ang )
y = sin( ang )[/QUOTE]
Thank you.
[QUOTE=Map in a box;31348535]Have us do OpenGL challenges to get open.gl release faster! PLEASE![/QUOTE]
open.gl ARG
[QUOTE=Map in a box;31348535]Have us do OpenGL challenges to get open.gl release faster! PLEASE![/QUOTE]
Help release open.gl faster! You can bring the release date of the ultimate OpenGL reference site closer from your very home! Simply complete the tasks below (in any order) and send your solutions to us before Friday the 29th of July!
1. Write it for us
[QUOTE=Wyzard;31345104]That first highlighted line is actually dereferencing an [url=http://www.cplusplus.com/reference/std/iterator/]iterator[/url], which is acts like a pointer in some ways but it isn't necessarily an actual pointer.
Anyway, the point of this code is do delete all the pointers that are stored in the vector. It iterates over the vector so that each time through, the iterator refers to one of the stored pointers. It dereferences the iterator to get the actual stored pointer, then calls delete on the pointer to free the Particle it points to.
The [code]particles.erase(it);[/code] is wrong in this case. Erasing an element from a vector makes the vector shift all the following items down to fill the gap. With the iterator moving forward one step each time through the loop, and all the remaining items moving [i]backward[/i] one step each time due to the erasures, it'll end up skipping every other item.
The intention was clearly to discard the pointers themselves in addition to the particles they point to, but doing it one-at-a-time like that is inefficient (even if it were implemented correctly) because each time one is erased, the vector has to spend time shifting all the remaining items down to their new positions, even though those remaining items are just going to be erased themselves in later iterations. It'd be much more efficient to just put a single [code]particles.clear();[/code] [i]after[/i] the loop. But in this case even that's not necessary, because the vector's own destructor will do it automatically at the end of the Space destructor.[/QUOTE]
Thanks a lot. I read that a couple times... I'll probably read it some more again.
What I don't get the most is that Particle* p is pointing to another pointer (which is the dereferenced iterator). Deleting Particle* p means that the pointer in the vector is also deleted...? I thought if you deleted a pointer, it just deleted the pointer and not what the pointer was pointing to? Or am I just not thinking clearly at the moment?
[QUOTE=thf;31345773]Yeah, but I still feel like it should be [b]a lot[/b] easier to learn C++ after understanding C properly. I just need help with where to learn about the standard library and the STL. (Because I'm supposed to know those properly before getting started with SFML, right?)
[editline]1:11[/editline]
Is [url=http://www.sgi.com/tech/stl/]this[/url] a good place to learn it?[/QUOTE]
STL was a bitch to learn, but it's really powerful once you get to know it. I mainly learned off:
[url]http://www.cplusplus.com/reference/stl/[/url]
There are a lot of example code on there which make it very helpful. :smile:
Question about quaternions:
Say I have all the vertex positions of an arbitrarily rotated cube (and, by corollary, all the surface normals).
How would I find a quaternion that rotates a cube from a standard orientation (identity quaternion transformation results in itself) to that rotated cube's orientation?
If you know how to do this with rotation matrices, that would be helpful too.
[b]Update:[/b]
I figured it out. Use the plane the cube is sitting on. Then, calculate the left vector of the resulting quaternion (calculated from between the global forward vector and the aforementioned plane). Find the quaternion between that left vector and the left vector of the cube. Now, multiply the conjugates of those quaternions (in order of how they are listed here), and viola!
Can someone tell me what a fragment is in GLSL?
Well, I'm stuck again. I honestly have no clue where to even start here so I'll just give you guys the description of the assignment I'm working on;
[quote]
Write a fraction class whose objects will represent fractions. You should provide the following member functions:
Two constructors, a default constructor which assigns the value 0 to the fraction, and a constructor that takes two parameters. The first parameter will represent the initial numerator of the fraction, and the second parameter will represent the initial denominator of the fraction.
Arithmetic operations that add, subtract, multiply, and divide fractions. These should be implemented as four value returning functions that return a fraction object. They should be named AddedTo, Subtract, MultipliedBy, and DividedBy.
A boolean operation named isGreaterThan that compares two fraction objects to determine whether one fraction object is greater than the other .
Another boolean operation named isEqualTo that compares two fraction objects for equality.
An output operation named print that displays the value of a fraction object on the screen in the form numerator/denominator.
Your class should have exactly two data members, one to represent the numerator of the fraction being represented, and one to represent the denominator of the fraction being represented.
When adding or subtracting fractions, remember that you must first find the common denominator. The easy way to do this is to multiply the denominators together and use that product as the common denominator.
project 3 folder should have the following files:
fraction.h (class specification file)
fraction.cpp (class implementation file)
client.cpp (client code using the fraction class)
[/quote]
And my teacher supplied us with client code that we're supposed to use, and I guess reverse engineer into a program.
[cpp]
#include <iostream>
#include "fraction.h"
using namespace std;
int main()
{
fraction f1(9,8); //calling a parameterized class constructor
fraction f2(2,3); //calling a parameterized class constructor
fraction result; //calling a default class constructor
fraction f3; //calling a default class constructor
cout << "The result starts off at ";
result.print(); //calling an observer function
cout << endl;
cout << "The product of ";
f1.print();
cout << " and ";
f2.print();
cout << " is ";
result = f1.MultipliedBy(f2); //a class binary operation - function
result.print();
cout << endl;
f3 = result; //assignment
if (f2.isGreaterThan(f3)){ //a class relational expression - boolean operation/function
f2.print();
cout <<" is greater than ";
f3.print();
cout<<endl;
} else {
f2.print();
cout <<" is less than ";
f3.print();
cout<<endl;
}
cout << "The sum of ";
f1.print();
cout << " and ";
f2.print();
cout << " is ";
result = f1.AddedTo(f2); //a class binary operation - function
result.print();
cout << endl;
cout << "The difference of ";
f1.print();
cout << " and ";
f2.print();
cout << " is ";
result = f1.Subtract(f2); //a class binary operation - function
result.print();
cout << endl;
if (f1.isEqualTo(f2)){ //a class relational expression - boolean operation/function
cout << "The two fractions are equal." << endl;
} else {
cout << "The two fractions are not equal." << endl;
}
const fraction f4(12, 8);
const fraction f5(202, 303);
result = f4.DividedBy(f5); //a class binary operation - function
cout << "The quotient of ";
f4.print();
cout << " and ";
f5.print();
cout << " is ";
result.print();
cout << endl;
system ("PAUSE");//exclude statement if not using Dev-C++
return 0;
}
[/cpp]
So a few main questions I have are;
1.) Where do I start on this?
2.) When I write a struct- say:
[cpp]
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
struct demoStruct
{
string yourname;
demoStruct()
{
yourname = "unknown";
}
};
int main(int argc, char *argv[])
{
cout << "Enter your name: ";
cin >> demoStruct.yourname;
system("PAUSE");
return EXIT_SUCCESS;
}
[/cpp]
why does it tell me "expected primary-expression before '.' token"?
I don't get how I'm assigning it wrong or whatever but if you could show me what I'm doing wrong that'd just be awesome.
Thanks whoever can help me with this, I've been reading all his lectures for the past two days with no avail so we'll see.
[QUOTE=awfa3;31356447]Can someone tell me what a fragment is in GLSL?[/QUOTE]
In most basic cases, a "pixel" that is part of a polygon that is being rendered.
[editline]27th July 2011[/editline]
[QUOTE=agnl;31356742]why does it tell me "expected primary-expression before '.' token"?[/QUOTE]
You're calling a type's method. You need to instantize that structure first, then call that method on an object. You can't have static structure members in C or C++ (as far as I know).
If you want to just have a struct instance in memory, you can do this:
[cpp]struct {
unsigned int AirspeedVelocity;
// ...
} g_AfricanSwallow;
// ...
g_AfricanSwallow.AirspeedVelocity = 30;[/cpp]
This is different to declaring a struct type:
[cpp]struct TSwallow {
unsigned int AirspeedVelocity;
// ...
};
// ...
struct TSwallow g_AfricanSwallow;
struct TSwallow g_EuropeanSwallow;
// ...
unsigned int AverageVelocity = (g_AfricanSwallow.AirspeedVelocity + g_EuropeanSwallow.AirspeedVelocity) / 2;[/cpp]
[QUOTE=q3k;31356755]]
You're calling a type's method. You need to instantize that structure first, then call that method on an object. You can't have static structure members in C or C++ (as far as I know).
[/QUOTE]
If that's true then why does this compile without any errors?
[cpp]
// This program demonstrates the use of a nested structure.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct CostInfo
{
double food, // Food costs
medical, // Medical costs
license, // License fee
misc; // Miscellaneous costs
};
struct PetInfo
{
string name; // Pet name
string type; // Pet type
int age; // Pet age
CostInfo cost; // A PetInfo structure has a CostInfo structure
// nested inside as one of its members
PetInfo() // Default constructor
{ name = "unknown";
type = "unknown";
age = 0;
cost.food = cost.medical = cost.license = cost.misc = 0.00;
}
};
int main()
{
// Define a PetInfo structure variable called pet
PetInfo pet;
// Assign values to the pet member variables.
// Notice that cost.misc is not assigned a value,
// so it remains 0, as set by the constructor.
pet.name = "Sassy";
pet.type = "cat";
pet.age = 5;
pet.cost.food = 300.00;
pet.cost.medical = 200.00;
pet.cost.license = 7.00;
// Display the total annual costs for the pet
cout << fixed << showpoint << setprecision(2);
cout << "Annual costs for my " << pet.age << "-year-old "
<< pet.type << " " << pet.name << " are $"
<< (pet.cost.food + pet.cost.medical +
pet.cost.license + pet.cost.misc) << endl;
system("PAUSE");
return 0;
}
[/cpp]
[editline]27th July 2011[/editline]
Got it, it's because I didn't quite understand structs but the fact that they're their own data type means I have to declare them then use them. Anyway, my original question about my fraction problem still stands, I have no idea where the fuck to start.
[QUOTE=Chrispy_645;31353451]What I don't get the most is that Particle* p is pointing to another pointer (which is the dereferenced iterator).[/QUOTE]
No, it's pointing to a Particle object. It's been [i]assigned from[/i] a dereferenced iterator; that's different from [i]pointing to[/i] a dereferenced iterator.
The "particles" vector contains a bunch of memory addresses of various Particle objects. The "it" iterator refers to a position within the vector — you can think of it as holding a number like 0 for the first element, 1 for the second, and so on. The line [code]Particle *p = *it;[/code]
means to go to the place in the vector that the iterator indicates, take the address that's stored there, and copy it into the newly-declared "p" variable. Now "p" holds the address of a Particle object, the same address that's stored in one of the slots of the "particles" vector. But "p" has no further connection to the "particles" vector. It's no different from assigning one int variable to another; you end up with two unrelated variables that happen to contain the same number.
[QUOTE=Chrispy_645;31353451]Deleting Particle* p means that the pointer in the vector is also deleted...? I thought if you deleted a pointer, it just deleted the pointer and not what the pointer was pointing to? Or am I just not thinking clearly at the moment?[/QUOTE]
The "delete" keyword is a little misleading because you use it on a pointer, but it doesn't actually change the pointer at all; it deletes the object that the pointer points [i]to[/i]. You're left with a [url=http://en.wikipedia.org/wiki/Dangling_pointer]dangling pointer[/url], holding the same address that it did before, even though there's no longer a valid object at that address.
It's good practice to set a pointer to NULL after deleting it if the pointer itself will stay in scope for awhile — that way you can tell that it doesn't point to anything. In this case there's no need, since the pointer goes out of scope a few lines later anyway. After the loop finishes you're left with a vector full of dangling pointers (assuming you removed the broken erase() call) since the objects they point to have all been deleted by the loop, but they get thrown away by the vector's destructor immediately afterward, so that's OK too.
Thank you very much, I appreciate it.
It was mostly the delete keyword which got me confused. I thought "delete p" meant "delete the pointer p". :smile:
BTW, although it's important that you practice with pointers to understand how they work, for real-world programs I wouldn't recommend actually [i]using[/i] raw pointers like this. Instead use "smart pointers" that automatically delete their objects when they go out of scope, like std::auto_ptr (but you can't put thsoe in a std::vector) or std::tr1::shared_ptr (if your compiler supports it).
[QUOTE=Wyzard;31360198]BTW, although it's important that you practice with pointers to understand how they work, for real-world programs I wouldn't recommend actually [i]using[/i] raw pointers like this. Instead use "smart pointers" that automatically delete their objects when they go out of scope, like std::auto_ptr (but you can't put thsoe in a std::vector) or std::tr1::shared_ptr (if your compiler supports it).[/QUOTE]
If you're developing applications or games, that is.
If you're writing a codec or running some sort of feedback loop, you probably can't afford that overhead.
-snip again-
Keep posting updates in WDYNHW.
Sorry, you need to Log In to post a reply to this thread.