cocos2dx c++ appending a vector to a vector - cocos2d-x

How do I concatenate two cocos2d::Vector s?
cocos2d::Vector<FiniteTimeAction*> V1;
cocos2d::Vector<FiniteTimeAction*> V2;
I want to have V2 appended to V1;

cocos2d::Vector has overloaded pushBack which takes a vector and pushing it back to another.
V1.pushBack(V2);
CCVector.h
/** Adds a new element at the end of the Vector. */
void pushBack(T object)
{
CCASSERT(object != nullptr, "The object should not be nullptr");
_data.push_back( object );
object->retain();
}
/** Push all elements of an existing Vector to the end of current Vector. */
void pushBack(const Vector<T>& other)
{
for(const auto &obj : other) {
_data.push_back(obj);
obj->retain();
}
}
P.S what is unclear why they do not re use pushBack(T object) in overloaded pushBack(const Vector& other)

Related

Remove element from struct array

I need help on this. So my task is to write a function that inputs an array of structures and two variables x and y. The structure is an angle structure, so it has degrees, minutes and seconds. The function should delete all elements in the array whose value in radians is between x and y.
So basically something like this:
struct Angle a[]={{6,10,10},{11,20,20},{30,30,30}};
The output should be {30,30,30}.
In the function I returned "size-count" because I just want to know how many elements I have left in the array so I know to where my for loop should go in the main function.
I think that my program doesn't even enter the if statement and I don't understand why.
Sorry if my code is confusing. I'm a beginner programer.
struct Angle
{
int degree,minutes,seconds;
};
int removeelement(struct Angle *a,int size,int x,int y)
{
int i,j,count=0;
double radians;
for(i=0;i<size;i++)
{
radians=((a[i].degree+(a[i].minutes+a[i].seconds/60)/60)*pi)/180;
if(radians>=x && radians<=y)
{
count++;
for(j=i;j<size-1;j++)
{
a[j]=a[j+1];
}
}
}
return size-count;
}

Explanation to why two constructors are required

Unfortunately, I do not feel confident with my understanding of default constructors.
I have searched extensively to find a resource that provides an explanation to adhere to my personal learning curve of the Java language. However, upon completing an assignment, I feel I may not be meeting the assignment criteria due to my own feeling of redundancy to need for a default constructor. This is why i feel like i am misinterpreting the concept of different types of constructors all together.
I have created two constructors as the assignment requires. One that takes in no parameters and initializes instance variables to a default value. And another that takes in parameters to give values to the object variables when the new object is created in the main method.
Why am I creating a default constructor for the object if the default is never used in the main method? Below is a sample of my code:
public class Circle {
private double x; // declaring variable to hold value of x coordinate
private double y; // Variable to hold value of y coordinate
private double r; // Variable to hold value of the radius of a circle
/* default constructor */
Circle() {
x = 0.0;
y = 0.0;
r = 0.0;
}
/* constructor takes in three parameters and sets values for variables x, y, and r */
public Circle(double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
// test class created for main method
public class TestCircle {
public static void main (String[] args){
Circle c1 = new Circle(2.0,3.0,9.0);
System.out.println();
System.out.println(" A circle object has been created with the following attributes:");
c1.printAttributes();
System.out.println();
System.out.println("The circle is tested for the maximum radius of 8.0...");
c1.setRadius(8.0);
System.out.println();
System.out.println("... since the radius is more than the allowable maximum, the new attributes for the Circle are:");
c1.printAttributes();
System.out.println();
System.out.println("The area of the Circle is " + c1.area());
System.out.println("The Circumference of the circle is " + c1.circumference());
System.out.println();
System.out.println("The origin of the circle is now moved by a specified amount...");
c1.move(6,-7);
System.out.println();
System.out.println("The new attributes of the circle are:");
c1.printAttributes();
System.out.println();
System.out.println("Testing if the point (10,-20) is inside the circle...");
System.out.println();
if (c1.isInside(10,-20)){
System.out.println("The point (10,-20) is inside the circle");
}
else {
System.out.println("The point (10,-20) is not inside the circle");
}
} // end of main
} // end of class
If you don’t use it you should delete it. Sometimes you will need to create empty objects in order to set attributes a posteriori, but if you are not using it at all there is no point to have it
The point of making default constructors is sometimes for back end stuff and is considered a "good programming practice" no you don't use the default constructor here in your main and in fact your code would run just fine with no default constructor comment it out and re run your tester you will see it works fine.

Cannot invoke mult(float) on the primitive type float

I'm working on a simple gravity program in Processing. My program takes particles and attracts them to each other based on the formula for gravity. Unfortunately, once I try to multiply the force to the direction with PVector.mult(), I get the error in the title:
Cannot invoke mult(float) on the primitive type float.
Here is my code for the method. G is defined elsewhere.
public float distance(Particle other) {
return location.sub(other.location).mag();
}
public PVector direction(Particle other) {
return location.sub(other.location).normalize();
}
public void gravity(Particle other) {
float grav = (G*((mass * other.mass)/pow(distance(other), 2)));
if(distance(other) != 0) {
acceleration.add(distance(other).mult(grav));
}
Why am I not able to pass a float where a float is due?
Let's take this line apart and split it into multiple steps:
acceleration.add(distance(other).mult(grav));
Here's my attempt to split it into multiple lines:
float grav = 42;
float distanceFromOther = distance(other);
float multipliedValue = distanceFromOther.mult(grav);
acceleration.add(multipliedValue);
Hopefully this makes it more obvious what's going on: you're trying to call mult() on a float value, which won't work. You need to call mult on a PVector or another class that contains a mult() function.

Swing JTable - Unable to repaint and change background of cells

Hy everyone,
I'm trying to do some calculations in a JTable after iteration and mark with different background the cells that I need.
However, I have 2 problems at the moment:
1) Cells are not painted immediately, but after the whole iteration cycle
2) Areas are not painted properly - if I need to paint table[3, 4] and table[6, 5] it draws a rectangular from [3,4] up to [6, 5] instead of drawing the singular cells only.
About problem 1: could I call repaint() with priority without the need to finish everything and the JVM to decide whenever to paint? I try to do fireTableCellUpdated() and fireTableDataChanged() but they don't get updated.
Here there is my custom cell renderer method that changes the BGcolor:
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row,int column) {
Component renderer = super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
if(value instanceof Color) {
Color c = (Color) value;
renderer.setBackground(c);
System.out.println("BG change [" + row + ":" + column + "]");
}
return renderer;
}
Here there is the loop where I paint my cells on a button click:
for(int paintJ = startIndex; paintJ < endIndex; paintJ++) {
CrossCellRenderer rend = (CrossCellRenderer) jTable1.getCellRenderer(i, paintJ)
.getTableCellRendererComponent(jTable1, Color.blue, true, true, i, paintJ);
crossTableModel.fireTableCellUpdated(i, paintJ);
jTable1.revalidate();
jTable1.repaint();
try {
Thread.sleep(1000);
} catch(InterruptedException ie) {
System.err.println("Exception sleeping the thread.");
}
}
Any tips on that?
Hate to say: but you do it (whatever you want to reach) completely wrong ;-)
Never-ever do any direct manipulation/paint on a renderer, instead change the model data and the rest will happen automatically.
Never-ever call any of the fireXX methods on a model from outside the model, it's the exclusive responsibility of the model to notify
its listeners on change
Never-ever (or very very rarely, certainly not here ;-) there's a need to call revalidate and/or repaint dircectly, will happen
automatically if a model is well-behaved
....
Best to read Snoracle's tutorial on howto-use tables to fully understand the rendering mechanism
http://download.oracle.com/javase/tutorial/uiswing/components/table.html
Roughly:
// change the model, will notify its listeners
model.setValueAt(....)
// in a custom renderer, check the value and decorate as appropriate
public Component getTableCellRendererComponent(....) {
// ... normal config, f.i. done in super
Component comp = super.get...
if (myConditionForSpecialColor(table, value, ...) {
comp.setBackground(myColor);
} else {
comp.setBackground(normalColor);
}
}
// register the custom renderer
// per class
table.setDefaultRenderer(Object.class, myRenderer)
// or per column
table.getColumnModel().getColumn(myColumn).setCellRenderer(myRenderer)

Without using recursion how can a stack overflow exception be thrown?

Without using recursion how can a stack overflow exception be thrown?
Since no one else has mentioned it:
throw new System.StackOverflowException();
You might do this when testing or doing fault-injection.
Declare an ENORMOUS array as a local variable.
If you call enough methods, a stack overflow can occur anytime. Although, if you get stack overflow errors without using recursion, you may want to rethink how you're doing things. It's just so easy with recursion because in an infinite loop, you call a ton of methods.
The following applies to Windows, but most OSs implement this in a similar fashion.
The short answer is: if you touch the last guard page, it will throw.
An exception of type EXCEPTION_STACK_OVERFLOW (C00000FD) is raised when your application touches the bottom page of the stack, that is marked a PAGE_GUARD protection flag, and there is no room to grow the stack (commit one more page), see How to trap stack overflow in a Visual C++ application.
The typical case when this happens is when the stack has grown as the result of many function frames on the stack (ie. out of control recursion), as the result of fewer frames but very large frame sizes (functions with a very large local scoped object) or by explicitly allocating from the stack with _alloca.
Another way to cause the exception is to simply intentionally touch the guard page, eg. by dereferencing a pointer that points into that page. This can happen due to a variable initializion bug.
Stack overflows can occur on valid execution paths if the input causes a very deep nesting level. For instance see Stack overflow occurs when you run a query that contains a large number of arguments inside an IN or a NOT IN clause in SQL Server.
Every method call that has not yet returned consumes some stack space. (Methods with more local variables consume more space.) A very deep call stack can result in stack overflow.
Note that on systems with limited memory (mobile devices and such) you don't have much stack space and will run out sooner.
Short answer: if you have an object which calls an internal object, you increase the stack trace by 1. So, if you have 1000s of objects nested inside one another, each calling its internal object, eventually you'll get a stack overflow.
Here's a demonstration of how to generate primes using nested iterators:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
IEnumerator<int> primes = p.AllPrimes().GetEnumerator();
int numberOfPrimes = 1000;
for (int i = 0; i <= numberOfPrimes; i++)
{
primes.MoveNext();
if (i % 1000 == 0)
{
Console.WriteLine(primes.Current);
}
}
Console.ReadKey(true);
}
IEnumerable<int> FilterDivisors(IEnumerator<int> seq, int num)
{
while (true)
{
int current = seq.Current;
if (current % num != 0)
{
yield return current;
}
seq.MoveNext();
}
}
IEnumerable<int> AllIntegers()
{
int i = 2;
while (true)
{
yield return i++;
}
}
IEnumerable<int> AllPrimes()
{
IEnumerator<int> nums = AllIntegers().GetEnumerator();
while (true)
{
nums.MoveNext();
int prime = nums.Current;
yield return prime;
// nested iterator makes a big boom
nums = FilterDivisors(nums, prime).GetEnumerator();
}
}
}
}
There's no recursion, but the program will throw a stack overflow exception after around 150,000 primes.
If you're talking about C++ with a reasonable standard library, I image that this would work:
while (true) {
alloca(1024 * 1024); // arbitrary - 1M per iteration.
}
Details on alloca.
int main()
{
//something on the stack
int foo = 0;
for (
//pointer to an address on the stack
int* p = &foo;
//forever
;
//ever lower on the stack (assuming that the stack grows downwards)
--p)
{
//write to the stack
*p = 42;
}
}
You can allocate a few bytes in the stack as well.
static void Main(string[] args)
{
Span<byte> b = stackalloc byte[1024 * 1024 * 1024]; // Process is terminating due to StackOverflowException.
}
Easiest way to make a StackOverflowException is the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
SomeClass instance = new SomeClass();
string name = instance.Name;
}
}
public class SomeClass
{
public string Name
{
get
{
return Name;
}
}
}
}