mrnutty 761 Senior Poster

Yes If you are allowed to use STL's list, then list<account> listOfAccounts will do

mrnutty 761 Senior Poster

Oh right, you need to seed first.

#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <vector> 
#include <string>
#include <ctime> 

using namespace std;

int main(int argc, char *argv[])
{
    srand( time(0) ); //seed

    cout<<"Current Car Pool Riders/Drivers\n";
    cout<<endl;
    cout<<"Monday - Nathan\n";
    cout<<"Tuesday - Jimmy\n";
    cout<<"Wednesday - Cochran\n";
    cout<<"Thursday - Harris\n";
    cout<<endl;
    vector< string > drivers;
    drivers.push_back("Jimmy");
    drivers.push_back("Nathan");
    drivers.push_back("Cochran");
    drivers.push_back("Harris");
 
    std::random_shuffle( drivers.begin(), drivers.end() );
 
    string pick = drivers[0];
    cout<<"The Person Driving this Friday is - " << pick << endl;
    cout<<endl;
 
    system("PAUSE");
    return EXIT_SUCCESS;
}
NetJunkie commented: Worked like a charm :) +3
mrnutty 761 Senior Poster

If its to learn C++, then I suggest you to do this.

1) In a file list all of the participants name
2) From your program, read/store the participants name
3) Pick a random name and output

It will be easier if your program just shows the random person's name instead of having the user enter 'Go'

Alternatively, if you don't have a lot of names, then it might be easier to hard-code the names in a vector. And then shuffle it and pick a random name. Judging from your post it looks like you only have a few names. In that case, it might be easier to do hardcode it.

Here is a sample code that you can work with.

#include <iostream>
#include <algorithm> //to randomly shuffle
#include <vector> //our container
#include <string>
using namespace std;

int main(){
  vector< string > fruits;
  fruits.push_back("apple"); //add a fruit to our container
  fruits.push_back("orange");
  fruits.push_back("pear");

  //randomly shuffle the vector
  std::random_shuffle( fruits.begin(), fruits.end() ); //reorders the container in random order
  
  string pick = fruits[0]; //pick the first element, could be any since the container was 'shuffled'
 cout << "Today, you should eat " << pick << " for breakfast " << endl;

 return 0;
}
mrnutty 761 Senior Poster

I guess that depends on what is meant by permutation. I take a permutation of size n to contain all values from 0 to n - 1 and to contain each value only once. So, for n = 5, say, a valid permutation would be:
$p = 0,4,3,1,2$
but something like:
$p = 0,4,3,1,16$
would be invalid.

For this definition, I guess you could put a bunch of checks in front of the actual inverting loop:

void inverse ( const std::vector< unsigned >& p, std::vector< unsigned >& ip )
{
   if ( p.empty() )
       return;

   /* Check validity of range */
   if ( *std::max_element( p.begin(), p.end() ) == p.size() - 1 ){
      /* Handle this error */
      return;
   }
   /* Check for repeated values */
   std::vector< bool > used( p.size(), false );
   for( unsigned i = 0; i < p.size(); ++i ){
      if ( used[ p[i] ){
           /* handle repeated number error */
           return;
      }
      used[ p[i] ] = true;
   }

   /* No need to check for unrepresented numbers, since this condition is */
   /* implied true if we get to this point, so by now the permutation is  */
   /* good for inversion.                                                 */
   
   ip.resize( p.size() );
   for ( unsigned i = 0; i < p.size(); ++i )
      ip[ p[i] ] = i;
}

Does that sound reasonable?

There is no specification that says permutation cannot contain any value from 0 to UNSIGNED_INT_MAX. Permutation is a concept hence it doesn't make sense to say permutation of …

mrnutty 761 Senior Poster

>> ip.resize( p.size() );
>> ip[ p ] = i;

the problem as I mentioned is that the value of p can be much greater than p.size() therefore making the statement ip[ p ] a bug

mrnutty 761 Senior Poster

I never heard of 'inverted premutation' but it looks like your reversing the key to value mapping into value to key mapping. The fastest way you can do this is in linear time, since you have to go through the whole array, which your function does. But there are some redundancies in your code and a possible bug.

The redudent code is your tempIndex, there is no need for it since you can simply use 'i' as it does not change in the body, until next iteration. And a possible bug is that you have no way of knowing whether 'ip' array is big enough, especially since the range p is huge. As a result of this, your program now suffers from buffer overflow and hackers can use this as a means to hack your program.

So to make your program more efficient in space,although you have to sacrifice time, you can do something like this,

//assume result size is same as mapping size
void inverse(const unsigned mapping, const unsigned size, unsigned result){
 for(unsigned i = 0; i < size; ++i){
   unsigned newKey = mapping[i];
   unsigned newKeyIndex = _getKeyIndex( result , newKey, size); //returns a unique index, via hashing
   result [ newKeyIndex ] = i;
}

The _getKeyIndex returns a index from [0,size) and it handles any collision. Google hashing for implementation. In theory the worst time for the above function is quadratic, because of the hashing, but the average case for hashing is constant.

So …

mrnutty 761 Senior Poster

make sure you aren't creating 'out' over and over again, therefore overwriting data. And post your new code.

mrnutty 761 Senior Poster

umm something like so:

struct ConstantRandom{
  int randNum;
  bool isFirstTime;
 ConstantRandom(): isFirstTime(true), randNum(0){};
 int operator()(){
   if(isFirstTime){ randNum = rand();  isFirstTime = false;}
   return randNum;
};
int main(){
 srand( time(0) );
 ConstantRandom cr;
 int i = cr(); //i equals some random number
 int j = cr(); // j should equal to i

Basically your just saving a state

mrnutty 761 Senior Poster

Yes I figured from your post that Publication was a base class. If you want to, you can cast the publication to the derived class and take appropriate measure like so:

Book * bk = dynamic_cast(*it);
if(bk != null){
  //publication was a book so do book stuff with 'bk'
}
mrnutty 761 Senior Poster

First you loop solution is very inefficient, with regards to opening and closing files. Just open it once and close it once.

Next a solution to your problem is to have the classes have its own extraction operator. Check this link for more details.

mrnutty 761 Senior Poster

>>By the way, i have this feeling that if lets say i get the hang with one Lib and then move to another that the previous Lib ive learned would go to waste, is it something i should worry about?

That's kind of an awkward question. I mean, throughout the years you will learn how to use different libraries for different things. Everything is a tool and tools will and can be replaced.


>>P.S i was using Dark GDK lib but i did not like it as much because it did all the job for me while i didnt understood how the libs code-work is done, isnt SDL something similar?

Listen, I was like you at one point. For example not wanting to use an image loading library because I didn't want to use someone else's code. But when you get more mature, you come to realize that its not always about knowledge, its about productivity. In your free time its ok to learn new skills. But in real world you will be using some tool that you didn't write. So get over it ;).

And as for SDL, I would strongly suggest you to go for it, else you can learn OpenGL. What you should concentrate at this stage is not how to load a image or do a certain task, but you should concentrate on learning to program effectively. This can only be done by practicing to program. So grab something …

mrnutty 761 Senior Poster

Why don't you move away from console application, and move into more graphics? Use libraries like SDL to make a simple 2D game. That way you will enjoy what your doing and you will be learning.

mrnutty 761 Senior Poster

The first one is 'using' the second one is 'creating'.

mrnutty 761 Senior Poster

>>>>(because C++ doesn't do JIT in the same way as Java)

>>C++ does not do JIT at all.
I was actually referring to the tendency of some compilers to delay allocation of a variable until it's absolutely needed rather than doing it when the declaration is made.

Are you referring to pointers, or in general all data-types?

mrnutty 761 Senior Poster

>>This is static polymorphism in C++:
I don't get why that's called static polymorphism? All that's doing is generating multiple function for each type. There is nothing polymorphic about it. Polymorpic is more like a 1->many relationships, while that's like 1->1 relationship, that is each type has its own function. What do you think?

mrnutty 761 Senior Poster
// overloads the equivalence operator which allows two Words to be compared using ==
bool Word::operator==(const Word& rhs) const		
{
	if (_word == rhs._word)			  
		return true;
	else
		return false;
}

That compares another Word with the current Word. The current Word has its own '_word' variables, so it checks if the another Word( rhs )'s '_word' value is the same as the current Word's. In other words, it checks if rhs._word is equal to this->_word

mrnutty 761 Senior Poster

Maybe someone will correct me, but I believe its just convention. But WinMain does have extra parameter options than int main() which might become useful. But a thing to note is that returning in WinMain really doesn't do much since its returned value is passed to ExitThread instead of ExitProcess.

mrnutty 761 Senior Poster

make sure you have braces, {} , around the return statement

mrnutty 761 Senior Poster

I can change the ints to doubles in the first argument.

In the second argument, I can use int for K's instead of unsigned, but it would be better if I could funnel my unsigned into ints in a pow function to make it easier to deal with.

double pow( double a, unsigned b){
int c = (int) b;
return pow( a, b );
}

is that good?

That function will not do what you want, call it something else like so

double power(const double base, const double exponent){
 return std::pow(base,exponent);
}

Then you can pass your regular datatypes to that functionint res = power(2,4);

mrnutty 761 Senior Poster

can i create a....

double operator^ (double a, double b){
return pow(a,b);
}

and do something similar for integers?

No. I think you are using the wrong language,why not matlab?

mrnutty 761 Senior Poster

>> l<2^(K-1);

thats not correct, if you are looking for the power function, then you need to include cmath:

#include <cmath>
#include <iostream>
int main(){
 using namespace std;
 float res = std::pow(2.0f,4.0f); //2^4 = 16
 cout << res << endl;
}
mrnutty 761 Senior Poster

Waiting for IO uses no processor time. The processor is busy running other processes.

Maybe I'm confused. The clock() function returns an approximation of processor time used by the program. When I/O operation occurs, CPU usually sends the job to a IO processor and proceeds with other jobs until it gets interrupted right? So in that wait period, the CPU was busy doing something else, but there is still that wait period. So why shouldn't for example,

long s = clock();
cin.get();
long e = clock() - s;

'e' be some time unit? I'm not saying that CPU just waits for IO to be done, but I'm saying that there is this IO waiting time, in which although CPU does other useful work.

mrnutty 761 Senior Poster

Is gettimeofday() portable to windows as well? I am using Linux right now, but I will want this game to be portable. It looks like SDL can measure time in milliseconds, so I may end up using that. If gettimeofday() is portable it looks like it may work better.

If you want to use windows, check out queryPerformanceCounter, that's what boost uses if available.

EDIT: Oh I see, why not just use boost?

mrnutty 761 Senior Poster

http://linux.die.net/man/3/clock
clock() determines (to some approximation) the amount of CPU time used by a program.
Waiting around for I/O typically does not count.

If you want to measure the amount of elapsed time, as by your watch for example, then use the time() functions.

The clock() function returns an approximation of processor time used by the program

Waiting for I/O counts as it constitute to time used by processor for waiting

mrnutty 761 Senior Poster

Bad naming, time is already defined in ctime

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
	clock_t start = clock();
	cout << "press enter...";
	cin.ignore();
	clock_t finish = clock();
	double doneTime = float(finish-start)/CLOCKS_PER_SEC;
	cout << "you took " << doneTime << " seconds\n";
	return 0;
}
mrnutty 761 Senior Poster

>>char*** b_array_ptr

You can think this as a pointer to a 2D array of chars. Example will suffice:

#include <iostream>
using namespace std;

int main(){
 char ***ptr = 0;
 //dynamically initialize it
 const int WIDTH = 3;
 const int HEIGHT = 3;
 const int DEPTH = 3;
 
 ptr = new char**[DEPTH];

 //allocate memory
 for(int i = 0; i < DEPTH; ++i){
    ptr[i] = new char*[HEIGHT];
 }
 for(int j = 0; j < DEPTH; ++j){
   for(int k = 0; k < HEIGHT; ++k){
      ptr[j][k] = new char[WIDTH];
    }
  }

 //populate it
 for(int i = 0; i < DEPTH; ++i){
   for(int j = 0; j < HEIGHT; ++j){
     for(int k = 0; k < WIDTH; ++k){
          ptr[i][j][k] = 'A' + (i * j * k) % 27;
     }
   }
 }

  //print it
  for(int i = 0; i < DEPTH; ++i){
   for(int j = 0; j < HEIGHT; ++j){
     for(int k = 0; k < WIDTH; ++k){
          cout << ptr[i][j][k] << " ";
     }
     cout << endl;
    }
   cout << endl;
  }
 
 //deallocate it
  for(int i = 0; i < DEPTH; ++i){
   for(int j = 0; j < HEIGHT; ++j){
     delete [] ptr[i][j];
   }
    delete [] ptr[i];
  }
  delete [] ptr;
  return 0; 
}
fruitymo commented: Thank you for this! I understood the fact that char*** is a pointer to 2D array of chars but I struggled to allocate memory for all 3 dimensions. This comment has been of great help. +0
mrnutty 761 Senior Poster

what happens if we delete a pointer twice..??

The FBI, CIA, and the military comes to your house via dragon and breaths fire onto your soul sending you to hell for eternity to burn, simply because you deleted a pointer twice. So next time be aware.

mrnutty 761 Senior Poster

I though it was obvious that Obama was going to get reelected? The main reason being, that during his presidency, Osama was killed.

mrnutty 761 Senior Poster

Make your class as such:

class dm_energy_vec
{
public:
        dm_energy_vec(){}
        dm_energy_vec(const vector<float>& vec): m_energy_dep(vec){}
	vector<float> m_energy_dep;
};

and in line 40, change to:

energy_dep_sum.push_back( dm_energy_vec(energy_dep));

but honestly see no point for that class.

mrnutty 761 Senior Poster

You do not want remove, but list::erase. Here is your code with tags and a little more cleaned up:

cout << "Contents: ";
list<FileInfo*>::iterator p = futurelist.begin();
while(p != futurelist.end()) {
  cout << (*p)->submissiontime << " ";
  cout << (*p)->length << " ";
  cout << (*p)->finishtime << " ";
  const int length = (*p)->length;
  if(length < averageBW){
   ++Noactive;
  }else{
   ++Nodelayed;
  }
   p = future.erase(p) //no need to increment p, since .erase returns the next element
}
cout << "\n\n";

But if that doesn't solve your problem, please be more specific.

EDIT: the reason why it james is because after you call .remove(*p), the iterator *p is invalid.

mrnutty 761 Senior Poster
while(begin != end )  
    words[*begin++]++;

is the same as:

while(begin != end )    //<-- I believe the stream iterator is getting input here
 {    
    int count = words[*begin]; //get the value for the given word
    words[*begin] = count + 1; //increase the count by 1 
    ++begin; //move to next word
 }
mrnutty 761 Senior Poster

It really up to the compiler to decide what to do on overflow. I don't think there is a standard mechanism to handle overflow. But a lot of compilers, wraps around the values.


And it seems like you need a variable that can hold the proper range, promote the variable to the next level and you need not to worry about it. If all the regular data types cannot hold the range that you need, then look into a arbitrary precision library.

mrnutty 761 Senior Poster

>>And of course, is it WORTH passing ints by reference?
No not really, unless you do need to modify the int. Reference and ints usually take up same size, so no noticeable advantage.

mrnutty 761 Senior Poster
foo(Matrix m); //makes a copy
foo(Matrix& m); //does not create a copy but now we are able to change m inside foo
foo(const Matrix m); //makes a copy, not allowed to change inside foo
foo(const Matrix& m); //does not create a copy and cannot change m inside foo

and no noticible performance boost from unsigned versus int. I just hate getting those "Warning: comparing signed and unsigned", so I just make the variable in the loop unsigned by default. If the variable doesn't need to be negative, then just make it unsigned. But making it int is no problem either, in most cases.

mrnutty 761 Senior Poster

>>And @firstPerson, <vector> is a header-only template library, why you bring up the aspect of loading DLLs beats me. This is just a question of include-guards (or header-guards). If you have #include <vector> twice, the only thing that is going to happen at the second #include statement is that the pre-processor will re-open the <vector> header-file, see the include-guard, skip to the end, and no code will be added as a consequence.

Oh ok. I was thinking something else.

mrnutty 761 Senior Poster

>>There is an error concerning lines 10-14. I had been using this code previously without errors. I'm not sure what I may have changed.

IT previously worked because you probably never used that function, so the program didn't instantiate it. But since now you are using it, the compiler instantiates it, and when it does, it sees a weird name called stringstream that it hasn't seen before, because in that file there is no definition or includes that says to the compiler that the weird looking name is defined. So to solve you problem, as suggested, include sstream, and then the compiler will see that the weird looking name has indeed been defined.

mrnutty 761 Senior Poster

Just some few points:

typedef std::vector<double> Vec; //Vector
typedef std::vector<Vec> Mat; //Matrix

Its just preference, but I think its more clearer if you say the full Name, maybe

typedef std::vector<double> RowVector;
typedef std::vector<RowVector> Matrix;

Use const-correctness when you can, for example:

////getColumn////getColumn////getColumn////getColumn////getColumn////getColumn
Vec getCol( Mat x, short b ){ //take's b'th column of x
    Vec y;
    for( short r=0; r<x.size(); ++r ) y.push_back( x[r][b] );
return y;
}

that function doesn't modify matrix x, so make it const Mat& x, remember to use reference when you can so you avoid making unnecessary copies. And there is no advantage of using short, just use int because the compiler might turn it into an int anways. Plus it feels like more convention to use int in loops rather than shorts, not to mention int's range is higher. So the resulting code might look like this:

Vec getColumn(const Mat& matrix,const int columnNumber){ 
 Vec columnVector(matrix.size()); //initialize its size to the amount of row
 for(unsigned row = 0; row < matrix.size(); ++row){
    columnVector[row] = matrix[row][columnNumber];
 }
 return columnVector;
}

In matrix and vector operations, people have all kinds of crazy operators that do different things, and in turn this makes it harder for the users. So Instead of defining a weird operator that isn't really standard, in terms of its use, just create a named function. For example you have,

////transpose////'////transpose////'////transpose////'////transpose////'////transpose////'////transpose////'
Mat operator~( Mat x ){ //transpose
    short n = x[0].size();
        Mat trans(n); // transpose
        for( …
mrnutty 761 Senior Poster

>>Why is it a bad idea to use the std namespace for my new functions? If all of my functions have names which are different than the names of std functions, it is no harm, right?

No do not do that. To avoid conflicts( perhaps in the future), you should strive for modularity. That is, think of namespace std as a unit which is part of the standard library, and now create your own namespace, and think of that as a different unit thats related to your application, and you may possibly have other namespaces from for example 3rd party library, and so you could think of those namespace as a different unit.


>>Also, it is more convenient because I won't have to write std::function every time I want to call a function in my program. (Or if my program uses the standard, I would have to use myname::function every time I want to use a function from my header file.)

What convenient for you might not be convenient for others. When you program you should program it so that it is easy to maintain. Although it might solve your solution right now, would it cause problems later on the road? Is your solution clear and intuitive?

And whats just one more line to solve your program? Don't be lazy, you can easily say using namespace MyOwnNamespace; and go on from there.

mrnutty 761 Senior Poster

PLease help me with these questions, I was interviewed for thses just today
Q1)Can we delare constant data members inside a class?
Q2)does friend function violates encapsulation/data hiding?
Q3)what are the types of polymorhphism you know?
Q4)why do you need virtual functions?
Q5)Can we do something like\
int & = NULL;
Q6)what are pragmas.Give an example?
Q7)what are the different ways to acces private members of a class?

1) Yes.
2) No.
3) Function overloading, dynamic ,static
4) For polymorphism
5) No
6) Used to avoid linking a file more than once, non-standard solution
7) If you in the class, and trying to access your private members, you can simply call it by its name, ex runPrivateFoo() or use the this syntax, as in,
this->runPrivateFoo()

mrnutty 761 Senior Poster

Its behavior is equivalent to :

//src via cplusplus.com

template <class InputIterator1, class InputIterator2, class OutputIterator>
  OutputIterator set_difference ( InputIterator1 first1, InputIterator1 last1,
                                  InputIterator2 first2, InputIterator2 last2,
                                  OutputIterator result )
{
  while (first1!=last1 && first2!=last2)
  {
    if (*first1<*first2) *result++ = *first1++;
    else if (*first2<*first1) first2++;
    else { first1++; first2++; }

  }
  return copy(first1,last1,result);
}

Note that the inputs needs to be sorted already. That is for this code set_difference(a.begin(), a.end(), b.begin(), b.end(), result.begin()); the vector 'a' and 'b' needs to be sorted already for the vector 'result' to contain the valid expected results. Other than that, you might just need to read up on the definition of set and its operations.

mrnutty 761 Senior Poster

Why the pointer in the first place? You could manage without it, can't you?

mrnutty 761 Senior Poster

Which goes against the more consistent policy of reading right to left. Both are valid, and since the OP's code used const on the right, I maintained that style.

Really? I thought it was more naturally to read things from left to right?

mrnutty 761 Senior Poster

Then the code should look like this:

string const& symbol::at(int index) const {
  assert(index < symbol_data.size());
  return symbol_data.at(index);
}

@OP this might be more clearer:

const string& symbol::at(int index) const {
  assert(index < symbol_data.size());
  return symbol_data.at(index);
}

So you can read it as 'constant string-reference' instead of 'string const-reference'. Both the produces the same result, take your pick.

mrnutty 761 Senior Poster

>>error: ‘template<class _Tp, class _Alloc> class std::vector’ used without template parameters
This error tells you your problem. You are using std::vector without templates. Why are you confused?

mrnutty 761 Senior Poster

The problem is in line 4. The user never entered anything so there isn't anything to discard, thus your first input gets discarded. And the rest follows. That's why you should first get the input and check for failure instead of checking for failure then getting the input and so on.

mrnutty 761 Senior Poster

You need to remove the redundant code and use a function:

int getInt(){
 int input = 0;
 while( !(cin >> input) ){
   cout << "\nPlease enter a valid input: ";
   cin.clear(); 
   while(cin.get() != '\n');   
 }
 return input;
}
int main(){
 int x = getInt() , y = getInt(), z = getInt();
}

But to answer your question, your ordering is wrong. See if you can figure it out.

mrnutty 761 Senior Poster

Thanks, this seems to mostly get the code working, however, I am still getting an error from another member function that I haven't listed here.

The call that throws the error is

vector<int> time;
current_data.grab(0).dump2ivector(1,time);

dump2ivector is declared as:

void csv_File::dump2ivector(int column, vector<int> &data) {....}

where {....} has inside of it a line like

data.push_back(atoi(access(0,0).c_str()));

Is there some problem with passing in a reference to a member function? That is the only thing I see special about dump2ivector

More specifically, the error is

error: no matching function call to csv_File::dump2ivector(int, std::vector<int. std::allocator<int> >&) const

Also don't name it time, because that might cause a name clash. Call it something like timeList or something.

mrnutty 761 Senior Poster

You should be returning by reference not by value

std::string & access(int row, int column);

csv_File & grab(int index);

And also provide a const reference version

mrnutty 761 Senior Poster

a) In a 32-bit system, a reference variable needs at least 4 bytes of memory and in a 64-but system, it needs at least 5 bytes. That's because a reference points to the memory of the variable its pointing to. Thus it needs only enough memory to store a memory address.

b) It will be a compile error because you have two of the same identifier/variable name.

mrnutty 761 Senior Poster

How do I invoke the int operator < instead of the int* operator < ?

vector<int*> pVec;
std::sort(pVec.begin(),pVec.end(), /*????*/);

Why do you need to store int* anyways? Either store it as vector<int> or vector< vector<int> >