tetron 22 Junior Poster

To load from a file you use std::ifstream

but your bigger problem is how do you know what shape you are loading?

since some shapes can require more data than others you don't know how to load the file

this is why I suggested using an ascii file so aswell as the data
you load the information to know
1 - how many shapes you have
2 - what is the current shape to load & therefore how much data

so then you could load the line of data or name depending upon your choice

check the name cast the shape * pointer and then load the remaining data.

so for a shape I would add the following methods

static std::string get_name();
bool is_my_name(std::string &name);
bool load(std::string &line);

if you load the file as std::ios::i

you can use get_line() until you get an empty line

check the line for the first word matching a shape_id
then

Shape * ps = 0;
//chop the 1st keyword
std::string shape_id = get_shape_id(line);
if(shape_id == square::get_name())
{
 square p_sq =  new square();
 p_sq->load(line)
 ps = p_sq;
}
else if(shape_id == circle::get_name())
{
circle p_cc =  new circle();
 p_cc->load(line);
 ps = p_cc;
}

if(ps != 0)
{
 data.push_back(ps);
}
///...

P.S. you probably don't need to post the entire code each time unless you have a bug

I have managed to sort out saving to a file, however I have …

tetron 22 Junior Poster

to save the data you need to save to a file

this uses #include <fstream> and std::ofstream fout there are plenty of articles on this
now you need a char * and know how many char need to be reserved if you want to save directly.

now you also need to convert and reinterpret your vector which requires converting to and from an array.

A more manageable appraoch writes to a txt file as ascii
now you can write your own header structure
so your file may look like:

shapes, 5
1,  triangle, 7.5
2, square, 3.4
3, rectangle, 7.8, 3.4

This adds a bit of overhead but it is readable by you

the idea is that you save a keyword add a number to tell you the size of a vector
then you have a line
with index, name, val1, val2, ....

This way shapes such as polygon can be of variable size

You would add a class called shape_helper

#include <vector>
#include <string>
#include "shape.h" //your shape class

class shape_helper
{
 bool save(std::string &file_name, std::vector<shape *> &data);
std::vector<shape*> load(std::string &file_name);
};

you still need to make sure you use delete to correspond to when you have finished with anything that you declared as new

tetron 22 Junior Poster

I don't use cin very often the easy solution would be to read in your input as a string variable and then parse the line.

So you could take in a string
and find a char say ':' and then you would have to convert the two sub strings into numbers.

but when playing with user input it is generally best where you can to get the user to adhere to a fixed rule and stick to it. The timesz when you would not do this is if you are dealing with information from a fixed source.

I am pretty sure that the operator >> could be overloaded to interpret reading into a time element and interpretting a single input and this probably already exists for date - time. You would use a class instead of a struct.

Please help how can i Cin two values in same line without a line break after first input stream..???

tetron 22 Junior Poster

The error that you are getting is complaining that there is no definition of a copy constructor. Yet normally this is created without you explicitly requiring it.

If I remember right your error is down to using fstream as a member variable I don't think that it is an object which can be copied and therefore the = on line 6 is your problem

the fix is not to have file as a member variable. Instead use a local variable in your FileToVector.cpp and then it should be ok

tetron 22 Junior Poster

other than your main function not having a return 0;
There isn't an obvious error on your merge function

You have not got any reference to a sort function in your code though.

tetron 22 Junior Poster

There are a huge amount of resources on minimising errors. Designing the idea before you charge in for classes is a good idea.

For this case the use of the word const would cause the compiler to pick up the error

void set(const int x);

another common mistake that can be difficult to spot is:

if(x = 0)
{
//this will not run and x has been set to 0 
}

you can write in reverse

if(0 == x)
{
//this would have given a compile error with single =
}

In the long term having a test class to test every function you write can be beneficial. but normally this is too time consuming to be attractive until things have gone wrong

The first thing that you want to do is comment your code so that you know what you intended to do later

Choose meaningful function names.

There are many other pitfalls to watch out for and you will get better at spotting them if you keep your code short and in classes you will be able to reuse your code and so you can know where the error is.

The last thing I would recommend is always use braces {} for any if
- Spotting a wrongly matched else when they are not used can be very difficult

Thank you very much, that fixed the issue. I always make one careless error like this. Anyone have any …

tetron 22 Junior Poster

It is not entirely clear what problem you are having from your description.

I assume that this is not just a memory leak that has arisen in your code from calling new() without delete.

But from a problem I had recently with new() giving a bad memory alloc exception. I found that visual studio has ~2Gb limit as an application. There are both compiler and OS issues with trying to load very large amounts of memory at once. This also has limits when the memory is being reserved for dynamic memory as it was doubling each time. If you are not using more than 1Gb then I imagine that you have a different problem.

REading very briefly about globalmemorystatus on msdn you are probably going to get an over flow error and so you would need GlobalMemoryStatusEx

Hi all,

How to find the free physical memory...
actually i want to avoid the exception from new operator..
i have used the GlobalMemoryStatus a windows api for this
but new is giving exception still more memory available than
i am allocating.

I am using visual studio 2005

Please help me....
Thanks in advance...

tetron 22 Junior Poster

This is unusual behaviour that you are getting and I would make sure as others mentioned that you are writing to a place that you should be able to write. I have had unusal interactions occasionally in the past and to minimise you could consider the following steps

It might be worth:

- creating a new project for the main in case their is some IDE corruption

- use an explicit file location equivalent to your My documents
C:\\Documents and Settings\\user\\

the \\ is needed for a single \
output the filename to screen to check the location

check that you can create a file in this folder using some basic program or copy and paste.

put everything in a try catch block and see if an exception occurs

I am not familiar with your OS and it could just be that the IDE does something odd to prevent the executable running but it doesn't sound like it should be behaving the way it is.

Hi - I copied and pasted your code in, and it compiled, but when I chose build and run, no file seems to have been written, but neither did I get the "could not open file" message (in my version, I did get the "File didn't open" message). I did a search for the file on the hard disk anyway, but got zero hits. I'm thinking I'll try it on the computers at the school …

tetron 22 Junior Poster
for (int i=0; i<bit; i++)
    {
        std::cout << bin[0]; // should be 11000
    }

the bin[0] will always just give you the first digit I expect you meant std::cout<<bin[i];

tetron 22 Junior Poster

I take it that this is your first time using classes

the first error tells you that there is no definition to the constructor

which it needs to create the object, as this can be in a .cpp file the compiler won't complain but the linker will!

so somewhere you need a piece of code like jonsca shows
just like your input function

//constructors have no return type
Rational::Rational()
{
//mthods go in here
}

Rational::Rational(int num, int den)
{
}

so link errors means that you either haven't written a function you use ot included the file in your project.

Error 1 error LNK2019: unresolved external symbol "public: __thiscall Rational::Rational(void)" (??0Rational@@QAE@XZ) referenced in function _main RationalNumbers.obj Assignment4

tetron 22 Junior Poster

I assume that your code outputs "cannot open file" and does not crash

it is normally a good idea to put markers next to chars when outputting as there are many chars that appear as space and sometimes buffers hold onto return characters for example.

I normally use is_open() method to check

One thing to try is to write a file using

#include <fstream>
#include <string>
#include <iostream>
int main()
{
std::string file_name("test_file.txt");
std::ofstream fout(file_name.c_str(), std::ios::out);

if(fout.is_open() == true)
{
//currently doing nothing other than create the file
fout.close();
}
else
{
std::cout << "could not open file!" << std::endl;
}

return 0;
}

the idea is to see where the file writes if it works but you can't see
the file search for it. In XP some applications can lock the file and stop you from opening another problem can be that characters in your string might not be what you think they are as wchar can look identical to chars and your compiler just assumes that the name is correct.

tetron 22 Junior Poster

fstream is how you read information to and from files and the syntax is messy but you will find their usage in lots of places

to read in from a file

#include <fstream> //needed for if stream class
#include <string>

int main()
{
//std is a namespace saying where ifstream can be found
std::string filename("C:\\some_file.txt");
//need to give file name as char * not std::string
std::ifstream fin(filename.c_str(), std::ios::in); //this opens an ascii file direclty
if(fin.is_open() == true)
{
/*
you can now use a memory buffer
char *buf = new char[max_bytes_to_read];
might use some of  the following methods
.read(); 
seekg();
.gcount();
getline();
*/
fin.close()
}
else
{
//could not open file
}
return 0;
}

This is not complete code but if you google read write c++ of fstream
you can find reference to the methods in fstream and examples

there are friendlier methods such as SALEM mentioned
but don't forget the std::

tetron 22 Junior Poster

Why not just iterate through the vector once
you have your test condition is_odd()
this has to be tested once per element if as you say it
is more complicted.
then add to v1 if true
and v2 if false

an example using std::vector<int>
sorting on the contents rather than the indices
if you want the indices this only requires adding and incrementing an int.

The sort algorithms seem somewhat slow to me as you only want to split not reorder

//std::vector<int> orig somewhere higher up
std::vector<int> v1, v2;
//if known estimare sz of two v1
v1.reserve(v1_sz);
v2.reserve(orig_sz - v1_sz);

std::vector<int>::iterator it_stop(orig.end());
for(std::vector<int>::iterator it(orig.begin(); it!= it_stop; ++it)
{
  if(is_odd(*it))
  {
     //condition 1 say is odd
     v1.push_back(*it);
 }
  else
  {
     //condition 2
     v2.push_back(*it);
  }
}

Naming convention is intentional, reminds me that unary predicate passed to remove_copy_if shall return negative result of what I want to copy ;)

PS1. Your solution also needs to check the whole vector items 2 times.

PS2. My current solution is based on what I've found in another thread, now it looks like that:

{
  ItemVector::iterator it = std::stable_partition(vec.begin(), vec.end(),isOdd);

  std::sort(vec.begin(), it, srt1); // no stable sort needed here

  std::stable_sort(it, vec.end(), srt2);
}

Thanks anyway :)

tetron 22 Junior Poster

google will show you lots of information and tutorials

I've found google often to be useful for programming
1 - type the problem into google
2 - find a link to daniweb
3 - normally I find a post on the subject from ancient dragon
;)

Sockets is something that if you are not making an assignment it is normally best to try to find code that you can reuse that has been implemented and tested elsewhere. Things perhaps to look into are topics such as web spiders and bots

tetron 22 Junior Poster

With template code you have to be careful on relying on the compiler. You can have broken code that the compiler does not complain about. Until you instantiate a class you cannot be sure that you have no conflicts.

Your singleton method seems a little unusual to me it may have something to do with the boost library with which I am not familiar.

If you use a static factory method it does not matter if the constructor is called more than once, this is why it is declared private/ protected. Otherwise you can have just a static int check > 0

//singleton factory method
class highlander
{
public:
//factory method get the one and only 
static highlander * create()
{
 if(pointer == 0)
 {
  //may want try catch to ensure new doesn't fail
   pointer = new highlander();
 }
return pointer;
}
private:
highlander() {//does nothing}

static highlander * pointer;
}

there are several singleton approaches and it depends on what you want
a single global
avoiding duplicates
just one at one time
one per template

But templating singleton there are several problems that might be created, your constructor looks odd to me as you are casting
this to T* but this does not inherit from T with singleton it is important to know what you are using it for.

Template classes are tricky to use with inheritence and you should only use them when you are sure that they …

tetron 22 Junior Poster

Thanks for the answers.
your comment that I might save a few nanoseconds is confusing. It seems to imply that some computation time might be saved.

You still have to type const just typing this once at about 0.4 seconds = 400, 000, 000 ns.

You rely on the compiler to write the machine code and using a high level language you should not expect a difference between the handling of a const int and an int, even if on some compilers you get a difference. The computer still can overwrite an area of RAM even if you declare it const.

Just as in theory:

const double sf(sin(pitch/2));

should be faster you should expect the compiler to give the same machine code and if you try to compensate for compiler short-falls eventually the compiler will be replaced and your code risks becoming slower overnight and you shorten the reusability life of your code.

Const is useful to keep your code readable and hence reusable - for a short scoped function there is very little benefit, and often refactoring your code means that you have to pass the variable across several methods and are better off with a class and member variable.

Its benefit is really in telling someone else who looks at your source code that your intention is for this value not to change.

similarly a return value of a function is an overhead and you cannot pass a constant variable as …

tetron 22 Junior Poster

Using sensors, pref motion detecting &heat-signature, & a camera. When the "intruder" gets into the room, camera records /captures the image. Then processes this image to discern if "intruder" is a real threat or just a dog. So this differentiation process is what I don't know if its image processing or ?

If you are trying to identify a person in a situation where they might actively be trying to deceive your sensors then you have a simple shape recognition problem.

In the first instance you need to be able to process your data to convert it into chunks that you can use. Which means avoiding having to write you own codecs

So to modularize your problem it is probably simplest to assume that you have a single frame and want to identify whether there is a human in the picture.

First you have have your motion sensors that tell you that there is something in the room, these have limited recognition benefits but if you are using a neural net it does not hurt to add in a module that tries to decide if it is a person based purely upon the motion sensors.

The other two sensors you have produce a displayable image and it is easiest to use data that you can recognise as your input. This means a single .bmp image either taken from the infra-red or ordinary camera.

Now you can get ordinary cameras that just take a sequence of …

tetron 22 Junior Poster

I get quite a ew warnings around 76

most of which are non referenced variables or
passing a function return to a

(std::string & )

with treat warning as error I get a
object not created error thay I assume is just because there is a warning.

I rebuilt in a new solution and everything runs :) so clearly there has been a corruption not directly caused by the code :(

The only things that I can think of are:

a dll is somehow attached to the process even though the files were deleted

the MFT has been screwed up so the release version is finding a non-current folder

a corruption in Visio

My concern is that if any of these things has happened the code might well be behaving unpredictably and I need to use the results.

Thanks again for the help.

Hmm, main is without parenthesis there, so I assume that you just typed that piece of code as an example, instead of copying it from the program's code.

Increase the warning level to the highest (W4) and rebuild the project. What does the compiler say?

yes typo leaving off ()

tetron 22 Junior Poster

Delteted Release folder and .ncb

and still it does not run.

It was worse than I though I had forgotten that the first line of
the main is a

#include <iostream>
/*
several other includes
*/

int main
{
std::cout << "wiki test" << std::endl;

/*
lots of other code
*/
return 0
}

there are no statc members, functions,
no globals
It does not even show the first line before hanging.

I left out <fstream> earlier as an include file in the project


THe above cout will build in an entirely new project int release

But I have run out of ideas.:confused:

tetron 22 Junior Poster

To go from the right hand side index to the left handside index the maths computationally is as follows

int cycle_rhs(3), cycle_rhs(6);
int temp =  x/cycle_rhs; //this gives a floor so no remainder
int temp2 = cycle_lhs * temp;
/*
0 , 1, 2 ->0
3, 4, 5 -> 6
*/
int offset_lhs(3);

y = temp2 + offset_lhs + x%cycle_rhs;

I note though that you are doing a matrix mthod why
not have a

std::vector<int> get_column(int id);
bool resize_matrix(int width, int height, int value = 0);
bool set_column(std::vector<int> &vals);

set of methods

I'm trying to find a formula for

copy[3] = b.data[0]
copy[4] = b.data[1]
copy[5] = b.data[2]
copy[9] = b.data[3]
copy[10] = b.data[4]
copy[11] = b.data[5]

letting the right hand side be b.data, I can see this is like

copy[3] = b.data[0] multiply by 2, add 3
copy[4] = b.data[1] multiply by 2, add 2
copy[5] = b.data[2] multiply by 2, add 1
copy[9] = b.data[3] multiply by 2, add 3
copy[10] = b.data[4] multiply by 2, add 2
copy[11] = b.data[5] multiply by 2, add 1

there's obviously a modulo pattern going on so I've tried

copy[i*2 + (rows +(-1*i) % (rows + 1))] = b.data_;

(rows = 3)

which gives me the adding pattern 3 2 1 0 3 2 1 0

however I need to miss out the 0, can anyone see how to do this?

Thanks in advance!

tetron 22 Junior Poster

It was a good thought, but the only code guard that I am using
is #pragma once I doubled checked my code and I am not using assert

It is console based appliction

and the only code that I am including in the project that is not self written is
<vector>, <string>, <iostream>, <map>

I will try a more rigourous approach by deleting the entire folder directly, then rebuild, but I can't do that for probably 1/2 an hour as I am in the middle of a slow Debug run:(


Is your code using assert() or any of the VS macros wrapped around assert() ?
Furthermore, have you written e.g.

#ifdef _DEBUG
.. do something here ..
#endif

If you have, then make absolutely sure that you are not changing anything via those pieces of code.

tetron 22 Junior Poster

It sound like quite an ambitious project if you don't have an idea of what algorithms to use.

You need to give a bit more information

What kind of recognition :
Camera footage - > simple recogniser or machine learning techniques are possible

Or are you talking about distinguishing between bot behaviour and a human. Here it tends to be repetitiion and efficiency that is the giveaway. And you need to think about what input you are using mouse movement, etc..

Without knowning the algorithm the only hints I can give is if you have a set of human and non-human data you could try reading about either
Hidden Markov models
or Neural Networks

Hello,

I have a software-based project of using human recognition algorithm to detect an intruder and be able to differentiate if the intruder is human or non-human.

Any ideas on what recognition algorithms I could use?:)

Thanks!

tetron 22 Junior Poster

Hi,
When using Microsoft Visual Studio, building in release the code just hangs and fails to execute but with Debug it builds and runs to the end. And I don't see why there should be a difference.

I did a shutdown then clean and a rebuild of solution but the behaviour persisted. I was wondering should there be any difference between the two versions or is this a sign that something else has gone wrong with my computer?


I am using classes that I use a lot, combined with a class I wrote tocombines two ordered vectors of strings each with an associated vector of ints.

In effect I am trying to merge two map<string, int> into one. The sizes move upto around 100000 elements

I am doing this with iterators, push_back and insert

other possibly pertinent facts:
- it compiled and built the release solution once today with code that should not have compiled as I had a bool function with no return.
- I am using absolute file locations on the same pc
- I had a crash earlier in release when the debugger complained of being unable to attach hook process.
- I am running XP and there is a virus circulating uni computers but I am unsure if my computer has been exposed
- I am processing a large number of files on my D: there is around 140Gb of 200Gb currently in …

tetron 22 Junior Poster

Template classes are only there to save you typing code
and in most cases it is not worth using them unless you
fully understand precisely what you need them before


The cleanest solution that is possible with my compiler
still requires that you explicitly declare what classes
you are going to be using via global pointers

tracker class keeps an id paired with a pointer
to allow random deletion and creation of pointers.


to get round the problem of the global in the tracker example I gave
we need a wrapper around tracker to allow one tracker for each type

this class is being called wrapped_tracker() and has methods that
should only be called when you know they are safe.

first declaring the types we will be using thus

wrapped.cpp

#include "wrapped_tracker.h"

wrapped_tracker<int> * wrapped_tracker<int>::my_tracker = 0;
wrapped_tracker<double> * wrapped_tracker<double>::my_tracker = 0;

//would add other types here

so the wrapper class is a singleton method
for each type t used:

wrapped.h

#pragma once
#include "tracker.h"


template <typename t>
class wrapped_tracker
{
private:
  wrapped_tracker()
    : pointer(0), b_tracker(false)
  {
    if(my_tracker != 0)
    {
      //have a tracker make my pointers right
      b_tracker = my_tracker->has_tracker();
      if(b_tracker == true)
      {
        pointer = my_tracker->get_pointer();
      }
    }
  }
  
public:

//factory method
  static wrapped_tracker * create()
  {
    if(my_tracker == 0)
    {
      my_tracker = new wrapped_tracker<t>();
    }
    return my_tracker;
  }

//important as cannot set local pointer in static …
tetron 22 Junior Poster

You are still trying to do the same the thing:

Why do you think you need gpglobals in the constructor?

You can get close to this with my second example but it really is unusual behaviour

In my last example I had a static method that probably a static pointer rather than a member variable

rather than calling classname x; directly

you call

classname * x = classname::factory();
x->method();

because factory is static you do not need an instance of the class
so the constructor is never called directly but this causes serious
memory handling problems and gpglobals must be explicitly set for all the types you might need. you can never know what is in gpglobals is valid!


The level of sophistication required to do what you are asking for is mainly so high as a result of you not really want this functionality, especially not templated
what you would have is a function that creates a spawnable and
adds it to a vector ie:

t get(int ind);
void add_t(t & to_add);
std::vector<t> my_vector;

If you read up on singleton methods this will be closer to what you wanted

IF you try the trackable example I gave this is as close to what you stated you wanted that you can get but your design is stil not correct at the paper level which is why you are getting confused.l

tetron 22 Junior Poster

With template classes you have to be very wary about compiler error messages. The code only gets built when it is needed and so the compiler does not compile using the template version but only when it knows what the type is.

You are trying to the following and the compiler is ignoring
it until you try to use it.

class c
{
public:
 c()
 {
     /*
         You cannot call the constructor  c()
         here as it will be an infinite loop
         if you have a std::vector<c> vc;
         when you try to add a c it is effectively
     */
      c x; //cannot call me infinite loop
      vc.push_back(x);
     /*
       therefore vc cannot work until c() is defined 
      a c* however can exist before c();
       but you only should add from new
     */
 }
int my_data;
};

you get the address from the instance not the compiler
int x(7);
int * px = &x;
There is no problem in declaring a vector to take a copy of an object
but your logic is inside out with the vector here which was the point I was trying to make earlier. You normally would not even want to have the functionality I showed in my second post.

The constructor doesn't know its own address if you want an address you need to call the new() via a factory method.

class c
{
private:
 c()
{
pointer = 0;
}

public:
static c *  get_me()
{
   if(pointer …
tetron 22 Junior Poster

Assuming that x1, y1, x2, y2, x3, y3

c = y3 - (y3 - y2) * x3 + a(x3^2 - x3*x2^2 + x3^3); (4)

is of the form c = k1 * a + k2; (a)
k1 and k2 are both directly calculable

combined with
c = k3 * a + k4; (b)
therefore
k1 * a + k2 = k3 * a + k4
(k1 - k4) = a * (k3 - k2)
a = (k1 - k4) / (k3 - k2);

from (b)
c = k3 *(k1 - k4)/(k3 - k2) + k4;
where
k1 = y3 - x3 * (y3 - y2);
k2 = (x3^3 - x3 * x2^2 + x1^3)
k3 = y1 - x1 * (y1 - y2);
k4 = (x1^2 - x1 * x2^2 + x1^3);

I have done this rearranging quickly so there is a small
risk of an algerbriac error

The only requirement is that k3 != k2
which is that none of the points are identical to each other

Having said this if this is not just trying to find the quadratic for
drawing a graph a more computer based task is probably wanted.

There are several other options you can use:
1 - a convergence technique
2 - Write code to rearrange simple formulae (like I have done)
3 - Matrix definition of the …

tetron 22 Junior Poster

I did not spot anything obvious but in the main
line 36
your while looks a little dangerous while(que.size() != 1) I would have expected while(que.size() > 1) as you are poping off two values.
I suspect that changing this will have no effect

When you create your new InternalNodes for temp
there is not a new() so the temp pointer will not point to valid memory you probably could do with cleaning up your new();
with delete

But I am probably missing the exact error

tetron 22 Junior Poster

as with any programming maths problem first you need to know
roughly what you are trying to by hand.

Another important factor in this instance is why you are doing it. If it is just to find the answer then just put the equation in a function. But if it is to use a particular set of programming tools then it is important to know which ones you have to use to solve the problem.

Are you trying to find a, b, & c
as finding the best fit to three points?

in which case you can either iterate in steps for a, b, & c
to see which values give the smallest error or rearrange
c = y1 - a * ( x1 * x1) - b * x; (1)
b * (x1 - x2) = (y1 - y2) + a * (x2 * x2 - x1 * x1); (2)

(1) ->

c = y1 - (y1 - y2) * x + a( x1* x1 - x1* x2* x2 + x1* x1* x1); (3)
you can use 3 with y1->y3 & x1->x3
like a simple simultaneous equation
to find c then a then b.

If the algebra is too scary even from here, you can iterate over 'c ' and find the values
of 'a' that fit then you can use these values to plot a graph

The matrix methods would be trickiest …

tetron 22 Junior Poster

Now the main problem with this function is that your nmax should be at least the size of of the elements in your matrix but ignoring
this problem

to see if an element exists simply means to check if getVal == 0;
this has an overhead so why no just reuse your code

//needs a bool to let you know
bool SetVal(int i, int j, double Val)
{
  bool ret(false);
if(rValid(i) == true && cValid(j) == true)
{
//valid coordinate so
ret = true;
  for(int c=0;c<3*nent;c+=3)
  {
     if(data[c]==i && data[c+1]==j)
     {
         //must be ok to set
         data[c + 2] = Val;
        return ret;
      }
   }
//we have a new coord
++nent;
 if(nent < nmax)
 { 
//original code for SetVAl
    int ind =3*nent;
   data[ind]=i;
   data[ind+1]=j;
   data[ind+2]=Val;
 }
 else
 {
  //overflow why you need a bigger max
  }
}
else
{
//coordinate out of range
}

return ret;
}

you should check that both matrices have same width and height before adding and subtracting


for multiplying you will have to change nmax = nr*nc /2; lose the /2
so

nmax = nr *nc;

the only thing that I have not covered is that if setVal takes a
Val of 0
that you will wnat to remove the entry from the list
and you might sort the list for a real application

void sMatrix::setEl(double r,double c, double val)
{
	int i;
	if (rValid(r) && cValid(c))
	{
		// when adding a …
tetron 22 Junior Poster

Identify a project that is of interest to you.

Do you have any boardgames that you like the advantage of picking such a project is that you can test that your design ideas
are implementable by making test versions of some of the design.

This will not be a waste of time as you might even want a final working version to play around with yourself for fun.

The other plus is that there are core elements such as the
display
logging positions
AI

and you have the option to extend the design to a multi-user web application with databases of ranks etc.

So that you have several options as to where you can stop your design.


Be careful not to pick something that you don't know how you
would design the modules. Remember this doesn't need to lead to an application that is better than anything else that exists it is about thinking through the design and viewing pitfalls. This should therefore include test modules to test your functions.

adcodingmaster commented: A good and brief reply. Thanks +0
tetron 22 Junior Poster

The get shape function currently requires the user to enter
max_row *max_column chars
which is 1000*1000 = 1 000 000 times
If you wish to test your function for big images
inputting the code will be arduous and time consuming.

There is not any point to having a very complex shape entered
if it is going to have to be entered everytime.

If this was a serious implementation you would allow input
from file but as this is only an assignment different rules apply.

I am assuming that your teacher is against file as you haven't covered it yet, but it allows you to input from either file or by hand
and even save the current shapes.

If you are not using file then you should allow a user the choice
of entering a big shape simply.
the easy shapes are square, rectangle and diamond.

You could add

std::cout << "0: manually enter shape" << std::endl;

to the menu
The difference is a square would require the user to enter just 1 number, and a rectangle, 2 numbers. Then a larger shape can be drawn with little effort by the user.

Edit:
I see this has become redundant

tetron 22 Junior Poster

First at some point you need to add the method for getting the user's input.

Your if loop is wrong because you should be using == to see if something is the same as something else
and this gives either true or false and if it is true the if will execute the code inbetween the {}
or the line following it.

there for when you say

else if(start_day = 1)//sets starts day to one and acts as >0 = true
day == "Monday";//this line does nothing

If you are being confused by this code try writing it in reverse

if(1 == start_day)//with single = this gives an error 
{
day = "Monday";//with  == this gives a warning
}

The other question is do you want to check

if(day == "Monday")
{
start_day = 1;
}

line 35 does nothing
line 39 you cannot put a string directly in an int

this is very higgledy-piggledy and you need to think about what you want to do at each stage and what information the computer needs to do things also if you have done functions this might help you clear-up the ordering of things

until you do the input it is not clear your intention

hello, i have been struggling with this program for a few days now, and have decided to get some feedback. The program lets the user input a number from 0-6 (0 representing sunday and 6 representing …

tetron 22 Junior Poster

When you say is there a more efficient way to get the shape than a txt file the answer is probably no. But it is always important to know what it is you are wanting the computer to do before you start programming.

Looking at you function get_shape it is not obvious what you are trying to with it.

It looks like that you are trying to load a char is this supposed to be used for the fill function? is this supposed to identify the shape?
Or is it supposed to load a shape into the memory?

If it is the first one then it is an easy fix.
I imagine identifying the shape is well beyond the scope of the problem. But you might have a choice of shapes say, square, rectangle, hexagon, triangle, circle.

Prompt the user for information to get them to choose the shape ie

cout << "Please choose a shape 1-5:" << endl;
cout <<  "1: square" << endl;
cout << "2: rectangle" << endl;
//other shapes 
int shape_id;
cin >> shape_id;

Then you would use shape id to select a draw method such as
the earlier method did with squares. I would recommend that you
stick to squares and rectangles until you get everything else working.

Then getsize()
are you trying to get the user to tell you how big the shape should be? If so you want to get a rectangle …

tetron 22 Junior Poster

I guess this is another thread that will be closed down and pointed to:

http://www.daniweb.com/forums/post1138190.html

Which is why this looks familiar :)

Part of the problem is this line in getVal: for (j=0;nent--;j++)

tetron 22 Junior Poster

Following-on from some of your comments in the thread that has been closed on this some basic things to note:

This is not a standard way of dealing with matrices and the name of
the class is misleading.

What is happening is that the data is being logged as a series of
points with each value having a row and column stored for it

In the constructor I am still uneasy about the nmax = nr*nc/2;
for your example nr = 3, nc = 3 so nmax = 4 (rounds down as int)
And therefore you can only have four records maximum even for a sparse matrix this can be an issue for adding.

As you have started to write your get_val needs to search the data
until it finds the point that you are looking for to find the value.

You have a mistake in your for loop stop condition: for(j = 0; nent--; j++) you are changing nent each time you go through the loop so when you set the next value...

When you add
+= (is a special function known as an operator so does not exist for your new class);
you need to add an element by
check size of M & N are the same
getting all of the elements from N
see for any element N != 0
then you need to find the i, j for …

tetron 22 Junior Poster
LinkedPQNode* current = NULL;
        current = queues[i]; // error is here

It is always useful to give full error code and all the initialisation but I am fairly sure I have spotted the error

You say queues is a SinglyLinkedList singlyLinkedNode * p_sll; could point to a LinkedPQNode because it LinkedPQNode is a type of SinglyLinkedNode that is what you tell the compiler when you use inheritence

but queues is not a type of LinkedPQNode so current cannot point to it;
I suspect you meant current->function(queue[i]); But I don't know what you want to do with the line that is failing
your while loop immediately after might well fail

I suspect that current is merely the wrong type of pointer

and you mean the equivalent to:

if(0 != queue[i])
{
 queue[i]->write(outfile);
}

but wanted a pointer to do some of the work but used the wrong pointer but be aware of what I said about streams as variables!

tetron 22 Junior Poster

I had a bit of a further play around with some of the code
and I suspect that there is part of your design that isn't quite right and that your class will struggle to do what you want.

This is an area where I haven't done much coding mainly because I always want to mix virtuals, statics and templates and the compiler
normally gives up and cry.

The problem with your design is that you have a class and
you want it to automatically add itself to a vector.

Now the problem is what do you want to happen when a variable dies. Either you need a class to manage the variables and tidy up rather than having a global.

Or the alternative I tried to write was to have a class
that managed itself but it still required a global to handle the static
member variable and therefore not fully templated as this would
have to be defined outside the class;

Therefore to template the my_tracker variable needs to be moved but I could not get it to work as a static variable of a template function probably can extern with a namespace but it all gets pretty ugly

tracker.h

#pragma once
#include <vector>

class tracker
{
public:
  tracker();
  ~tracker();
  int add(void * pv);
  std::vector<void *> * get_pointers();
  void del(int id);
private:
  std::vector<int> my_ids;
  std::vector<void *> * my_pointers;
  int next_id;
};

extern tracker*  my_tracker; //this …
tetron 22 Junior Poster

I mis-interpretted your question intially

Are you trying to make a self regitering class
in which case you probably want a vector of pointers
not objects

The problem is where do you define gpGlobals

when you create an instance of a class the template has to be defined
now as your code is in the constructor

vector<Spawnable<int>> gpPointers cannot be defined until apawnable is defined

and therefore cannot be used by Spawnable in its constructor

you can either have a vector<void *> and cast as needed dangerous

or have a different design so that you can

have a register method instead of just a constructor

/*templ_s.h all functions must be defined in .h
for templates
*/

#pragma once
#include <vector>

template< typename t>
//std::vector<templ_s<t> *> gpPointers;

class templ_s
{
public:
 typedef templ_s<t> tt;
 templ_s()
 {
 }
  
 void register_method(std::vector<tt *>  &my_pointers)
 {
   my_pointers.push_back(this);
 }

protected:
	t var;
};
#include "templ_s.h"
int main()
{
 templ_s<int> test;
 std::vector<templ_s<int> *> v_test;
 test.register_method(v_test);
 return 0;
}

otherwise a different method of handling is required and you need to
be very precise in your design requirements

tetron 22 Junior Poster
current = queues[i];

our old object files so I can't put any kind of access method in singilyLinkedList

When reusing old code it is still permissible to extend the class
as long as the extension does not alter any existing behaviour and the method is something meaningful to the code itself.

It is helpful if you post error codes and the piece of code where the problem line is.

But first a couple of observations: the code tags have highlighted remove as a keyword and so an alternative function name might be needed.

Second for the line you are using to work current = queues[i] There has to be a definition of operator[] if this is an array this should be fine and current needs to be a compatible pointer to queues

ofstream and ifstream are funny objects and cannot necessarily be passed into a function meaningfully. It is probably a good idea to place the ifstream and ofstream inside of the function and pass in a file_name.

write can fail and should return a bool

nothing else jumps off the page immediately - the error code is probably needed and the lines where you call the queues;

tetron 22 Junior Poster

Now there are some unusual things happening in your matrix class
normally a matrix stores the data
as a m by n array or vector of vectors

It is difficult to give exact answers without knowing if SetEl
is doing what you want

Say you wanted a matrix with m columns and n rows
then mathematically you need a value for each of the elements in the matrix

this is normally found using a column and row coord
like you are doing

but the data would be m*n doubles
this can be organised as a single list

so data would be a simple array or vector of values
and if you want column c & row r (starting from 0)
the index for the value you want becomes

index = r + m*c

so an init() method would create your data and then
you woud have a

void init(int number_of_cols, int number_of_rows);
double get(int c, int  r);
void set(int c, int r, double val);
bool valid_coord(int c, int r);
void clear();

These are the basic methods that you need
You have the outline for these methods with your constructor
being init(); it should be more like
nmax = nr*nc;
data = new double[nmax];

But I need to be sure that this is what you are trying to design


How would I go about? I've been …

tetron 22 Junior Poster

look at line 89 m[i,j] I expect your compiler is complaining that this is undefined
you need to define how to set_val in a matrix
I think you are missing a few storage

so

double val = m.get_val(i, j) + n.get_val(i,j);
m.set_val(i, j, val);

is the approach you need but you also need
somewhere to store the values in your matrix

tetron 22 Junior Poster

Why would you want be doing that kind of thing?

Good question it looks a lot like a HOOK and dll injection example piece of code.

Although, the fact I recognise it is probably not a good thing ;)

tetron 22 Junior Poster

I am trying to start the odometer reading at 0 to start with, but I want it to increase everytime the user inputs MilesDriven. I can't seem to get it to work...any ideas?

1st Do you know what a constructor is

in you class
add in the public Odometer(); there is no return

now this function gets called when you create
an Odometer now you can
set an intial value in this function
so you can make sure that you have set a value to 0
by calling Odometer_reset you can then return the value to 0

a function needs to be written like has been done for MPG()

tetron 22 Junior Poster

Is there a way to modify that function where it can get a different shape instead of just a box?

Yes, there are ways to modify it
and it is the general priniciple of putting things in functions is that it is easy to change

What you have to do to draw other shapes is define what you want to look like first

so you have a grid

0000#0000
000#0#000
00#000#00
0#00000#0
#########
000000000

You can draw a triangle like that
you will be able to find some examples on the web for this and
circle
I assume that you have some basic geometry:
A triangle is defined by three points

so you grid has an [row, column] for each cell
and you need to tell the computer when to draw a #

If you pick your three points as a coordinate
Then you can work out what the equation of the line would look
like for each side:

y = m*x + c

you have y1 & x1 for one corner and
y2 & x2 for the other this lets you find m & c via a
simultaneous equation

y1 = m*x1 + c (1)
y2 = m * x2 + c (2)

(1) - (2)
(y1 - y2) = m * (x1 - x2)
rearrange:
m = (y1 - y2) / (x1 - x2) (3)

programer411 commented: it was good +1
jonsca commented: Mor rep for this thread that never ends :) +2
tetron 22 Junior Poster

To test getshape() will take for ever if you don't get it right
what you need to do is to test your function first for ideas that you can check by hand.

1000*1000 inputs will take a long time so
use smaller MAX values
if you need something this big you will have to load from file
for now I recommend that you have a test get_shape() function
that just gives you a square and a display function so that you can see what is happening then run your own get_shape for a small input and see what happens when you call display
so you want to add something a bit like:

const int max_row(5), max_col(5);
void dummy_get_shape(char shape[max_row][max_col]);
void display_shape(char shape[max_row][max_col]);

int main()
{
	char my_shape[max_row][max_col];
	dummy_get_shape(my_shape);
	display_shape(my_shape);
	return 0;
}

//gets a big empty square
void dummy_get_shape(char shape[max_row][max_col])
{
	char edge('#');
	char empty('\0');
	for(int c = 0; c < max_col; ++c)
	{
		for(int r = 0; r < max_row; ++r)
		{
			char to_add = empty;
			if(r == 0)
			{
				//left edge
				to_add = edge;
			}
			else if(r == max_row - 1)
			{
				//right edge
				to_add = edge;
			}
			else if(c == 0)
			{
				to_add = edge;
			}
			else if(c == max_col - 1)
			{
				to_add = edge;
			}
			shape[r][c] = to_add;
		}
	}
}

void display_shape(char shape[max_row][max_col])
{

	for(int c = 0; c < max_col; ++c)
	{
		for(int r = 0; r < max_row; ++r)
		{
			std::cout << shape[r][c];
		} …
jonsca commented: Rep for this monster thread +2
tetron 22 Junior Poster

Don't forget that this is a simple homework problem. You don't want to confuse the OP by adding unstated requirements.

Sorry, not my intention to cause confusion, but I imagine this task
is designed to gradually introduce the idea of sorting and ordering numbers.

And the most important part of any design problem is identifying the different situations that your code has to deal with.

IMHO it is part of the stated problem that there might be duplication of values as there is nothing saying otherwise:
say you had : 1, 6, 7, 8, 9, 3, 5, 6, 4, 9, 3
in which case I would interpret the seond largest number as second in the ordered list:
9, 9 , 8, 7, 6, 6 , 5, 4, 3, 1
which would be 9 not 8

Now while ordering all the numbers is obviously a lot more complicated than the question warrants being aware that the above case is a situation that the problem setter might be expecting the code to deal with, is important and represents part
of the design procedure.

Even if you are deliberately ignoring duplicate numbers and saying the 2nd largest is 8. It should be explicitly stated, to show an awareness that this is something that has been considered.

iamthwee commented: G.A.Y -2
Nick Evan commented: iamthwee is being a little troll again +12
tetron 22 Junior Poster

I'm not sure what your answer, but here is what I believe is the answer :
Total Sum is = 24329559449000

My code I included only works out the bottom 10 digits so
9559449000
Guess you probably didn't need any help after all :)

I don't know if you wanted a broader approach to say calculating...

the last 128 digits from the sum of 1000 numbers to a random power I can go through method two if it will help.

I would recommend a computing approach over the mathematical sequences as it is difficult to format maths without paper and pencil.

tetron 22 Junior Poster

don't forget second largest value can be the same as largest value
so you will want to count how many times the first value appears in the second while loop too.

tetron 22 Junior Poster

There are good general prinicples of OO you are adopting. And when your code gets long you want to test things a function at a time.

I think there is a potential issue with the player choose function.
you might find it simpler to have a function to process the input
seperately as there is no error checking

atoi would normally take a c_string rather than a single char
so this might cause problems putting in the address of ones[1] but it might handle it ok but it would be safer to take everything but the first letter

string ones;
int col_id, row_id
cout << "enter a number " << endl;
cin >> ones;
if(ones.size() >= 2)
{
col_id = convert(ones[0]);
//get all but the first letter of ones
ones = ones.substr(1);
row_id = atoi(ones.c_str())
}
else
{
//error
}
//now check col_id & row_id are valid

so you might prefer putting in letter then a number
with two inputs that way if the user only entered one letter
your code will not fail.

also v[two - 1][onez -1] might go out of range if convert finds a non-letter if this happens your code will fail
as v[-1] does not exist
so you should check

this is the issue with your rand %8 is in range 0-7
%8 - 1 in range -1 to 6

a couple of minor things to consider

you have if() …

mitrmkar commented: good atoi catch +5