C++ Help?

Status
Not open for further replies.
I really don't entirely disagree, though I do think that convention is enough of a reason not to treat it as a hard rule. People getting tripped up reading your for loops can distract them from paying attention to what's really going on.

I do think that modern sources for learning C++ should switch to pre-increment, though. My go-to recommendation book, Accelerated C++, does pre- as a rule. Everyone learning C++ really should start with that book.
 
maharg said:
I really don't entirely disagree, though I do think that convention is enough of a reason not to treat it as a hard rule. People getting tripped up reading your for loops can distract them from paying attention to what's really going on.

I do think that modern sources for learning C++ should switch to pre-increment, though. My go-to recommendation book, Accelerated C++, does pre- as a rule. Everyone learning C++ really should start with that book.

Definitely agree there too. It's one of the only books that doesn't teach C++ as an extension of C.
 
I taught myself C++ from knowing almost nothing about programming period from C++ Primer. It really impressed me, especially once I skimmed a few other books in leisure.
 
Hi, I'm having a problem with some pointers and lists and so. I'm really in need for help, hope some of you can give me a hand.

Basically, I have a list made of nodes (a struct node I have created):
std::list<node> myList;

The node struct is like this:
struct node
{
int F, G, H;
struct node* right;
struct node* left;
}

I want to find a given element in that list.

What I'm trying to do if iterate through this list, and for each element, compare if this element to the one I'm looking for.

list<node>::iterator it;
node myNode;

for(it = myList.begin(); it != myList.end(); it++)
{
if(*it == myNode.right) //----------> THIS IS WHERE I HAVE PROBLEMS
{
//ok
}
else
{
//not ok
}
}


The error I'm getting is something like "error C2678: '==' binary: couldn't find an operator that adopts an operand in the left side of type 'cEnemy::node' (or there is now an acceptable conversion)"
Hope this error makes sense, I'm translating the sentence.

Does anyone have an idea?
 
FerranMG said:
Hi, I'm having a problem with some pointers and lists and so. I'm really in need for help, hope some of you can give me a hand.

Basically, I have a list made of nodes (a struct node I have created):
std::list<node> myList;

The node struct is like this:
struct node
{
int F, G, H;
struct node* right;
struct node* left;
}

I want to find a given element in that list.

What I'm trying to do if iterate through this list, and for each element, compare if this element to the one I'm looking for.

list<node>::iterator it;
node myNode;

for(it = myList.begin(); it != myList.end(); it++)
{
if(*it == myNode.right) //----------> THIS IS WHERE I HAVE PROBLEMS
{
//ok
}
else
{
//not ok
}
}


The error I'm getting is something like "error C2678: '==' binary: couldn't find an operator that adopts an operand in the left side of type 'cEnemy::node' (or there is now an acceptable conversion)"
Hope this error makes sense, I'm translating the sentence.

Does anyone have an idea?
it is a list<node>::iterator; therefore, *it is a node. On the other hand, node.right is a node* (from your node definition). I think you want to use something like &(*it) == myNode.right.
 
Wichu said:
it is a list<node>::iterator; therefore, *it is a node. On the other hand, node.right is a node* (from your node definition). I think you want to use something like &(*it) == myNode.right.

Thanks a lot.
It worked, and of course it makes a lot of sense, but as I was typing the post this morning I was about to pull my hair out. :P

Thanks again. :)
 
Ok so I have a challenge for you guys. I'm doing the exercises in Accelerated C++ and there is one question that is giving me trouble.

Use a library algorithm to concatenate all the elements of a vector<string>.

By library it refers to the C++ standard library, and more specifically the algorithm header file. Now, I do realize this problem is trivial without using the restriction above. Any ideas?
 
What is the best way to handle binary IO, whilst accounting for concurrency?

by that I mean should an object load itself?

i.e.

Code:
class bitmap
{
[INDENT]loadBitmap(string filename)
{[INDENT]std::ifstream in (filename);
//load data[/INDENT]
}[/INDENT]
[INDENT]char* data;[/INDENT]
};

Or should I pass a reference to an IO class of my own making around my application so I can cue up and dispatch IO commands?.

The reason I ask is because I am trying to avoid singleton's and global variables.

What happens if several threads both call iostream simultaneously?
 
Lasthope106 said:
Ok so I have a challenge for you guys. I'm doing the exercises in Accelerated C++ and there is one question that is giving me trouble.

Use a library algorithm to concatenate all the elements of a vector<string>.

By library it refers to the C++ standard library, and more specifically the algorithm header file. Now, I do realize this problem is trivial without using the restriction above. Any ideas?

The algorithm you probably want is mentioned on page 121. Technically it's not defined in <algorithm>, but it is a standard algorithm. I won't say any more than that because this is your homework.


dogmaan said:
What is the best way to handle binary IO, whilst accounting for concurrency?

by that I mean should an object load itself?

i.e.

Code:
class bitmap
{
[INDENT]loadBitmap(string filename)
{[INDENT]std::ifstream in (filename);
//load data[/INDENT]
}[/INDENT]
[INDENT]char* data;[/INDENT]
};

Or should I pass a reference to an IO class of my own making around my application so I can cue up and dispatch IO commands?.

The reason I ask is because I am trying to avoid singleton's and global variables.

What happens if several threads both call iostream simultaneously?

On different file handles? It's fine. Even to the same file (though if one thread is writing while another is reading that'll give you some strange results). Same handle is bad bear. Don't do it.
 
maharg said:
The algorithm you probably want is mentioned on page 121. Technically it's not defined in <algorithm>, but it is a standard algorithm. I won't say any more than that because this is your homework.

...

This is not homework. I doing this to re-learn C++.

I tried

Code:
copy(a.begin(), a.end(), back_inserter(b))

where a is a vector<string> and b is a string but that didn't work.

Then I tried transform with a global static string, but I was violating so many "good" practices is OO programming that it was clear a better solution exists.

I don't think the exercise is possible.

edit: Ok, I got it working by using accumulate as you suggested.

Code:
	string result;

	//copy(test.begin(), test.end(), back_inserter(suckIt));

	string finalResult = accumulate(test.begin(), test.end(), result);

	cout << finalResult ;

This is a surprise as I'd thought that accumulate only worked with numeric values. Is it working because string overloads the '+' operator? If that is the case then the function can be used with any type as long as the operator is overloaded.

Thanks for the hint maharg.
 
Lasthope106 said:
This is a surprise as I'd thought that accumulate only worked with numeric values. Is it working because string overloads the '+' operator? If that is the case then the function can be used with any type as long as the operator is overloaded.

Thanks for the hint maharg.

That is, indeed, the whole point of templated algorithms. They require certain operations to be defined in order to do their work, and they'll do that work on anything that has those operations. You could define your own type to be accumulated on with arbitrary values and it'd Just Work.

Also, just because you're not doing it for school doesn't mean it's not homework. The point of exercises like that is to go through different possibilities and figure out why they do/don't work.


poweld said:
Code:
a.insert(a.end(), b.begin(), b.end());

See: http://www.cplusplus.com/reference/stl/vector/insert/

You snipped out so much of the question you didn't answer it. ;)
 
I know its off topic but being junior i can not make thread.
in my university i have given a task to make a website that behaves like an os
e.g
Code:

http://www.silveos.com/


But i don't even know where to start what to learn.
the only things iv been told it that you can use silver light for gui and c# and asp.net for server side.And i know nothing about them.i have been given 6months time and this assignment is like first year project and will carry a grade so it will affect my cgpa.need help
 
Fezan said:
IBut i don't even know where to start what to learn.
the only things iv been told it that you can use silver light for gui and c# and asp.net for server side.And i know nothing about them.i have been given 6months time and this assignment is like first year project and will carry a grade so it will affect my cgpa.need help

Uhm, you have plenty of time... I would start by learning basic C# and writing a few simple console applications. After that move on and learn more about the ASP.NET and Silverlight frameworks.

EDIT: Just don't try to start on this project from the get go, you will have to get more comfortable with the underlying tools first.
 
Kalnos said:
Uhm, you have plenty of time... I would start by learning basic C# and writing a few simple console applications. After that move on and learn more about the ASP.NET and Silverlight frameworks.

EDIT: Just don't try to start on this project from the get go, you will have to get more comfortable with the underlying tools first.
best place to learn c#?Books?video etc
and will designing GUI require Photoshop or other skills ?
I usually start learning c#.i am able to understand loops and conditional statements.If a code is written in front of me i can somewhat understand it but whenever it comes to writing code for example making a text based game i am completely blank.Then i stop learning
 
Fezan said:
best place to learn c#?Books?video etc
and will designing GUI require Photoshop or other skills ?
I usually start learning c#.i am able to understand loops and conditional statements.If a code is written in front of me i can somewhat understand it but whenever it comes to writing code for example making a text based game i am completely blank.Then i stop learning
MSDN is a good place to start. A book is good as well, doesn't your university recommend one?

Also, some good programming exercises, as soon as you are familiar with the syntax of the language are on Project Euler. They are kind of math-y though and get pretty hard at a certain point.
 
Fezan said:
best place to learn c#?Books?video etc
and will designing GUI require Photoshop or other skills ?
I usually start learning c#.i am able to understand loops and conditional statements.If a code is written in front of me i can somewhat understand it but whenever it comes to writing code for example making a text based game i am completely blank.Then i stop learning

Is this for a final year design project? No Photoshop is needed to design a GUI unless you want to get real fancy.

First thing, you have to find what are the requirements of the application. What is the website supposed to do? You say it has to behave like an OS, then what does that mean exactly?

Does it have to support other application running on top of it?
You are probably going to need a console, and a file system.
And the ability to create other processes, threads, etc.

As for learning C#, there is a series of books by a publisher called Murach that I really like. All the books use a "paired-page" concept where the code, diagrams, etc is presented on one page and the explanation in the other.

http://www.murach.com/books/vba.htm

You can get them on Amazon for cheaper. With the help of their C# book I was able to code a C# windows form application that connects to a database in a couple of week, without having never done C# or .Net development in the past. Give them a try.
 
maharg said:
You snipped out so much of the question you didn't answer it. ;)
I thought the meat of the question was how to concatenate one vector onto another... maybe I shouldn't respond while at work and not really focused!
 
This is for C, but thought I'd ask it here since C++ is the closest thing to C

What's the most effective way to pair objects to use in a return function?

I have something similar to this (not the actual code):
Code:
pair(a,b)
{
	Obj* pair = malloc(sizeof(Obj*)*2);
	pair[0] = a;
	pair[1] = b;
	return list;
}
The issue here is that I need all the efficiency I can get for this and malloc is slowing things down. Obj* pair[2] causes a segfault.

edit: hmm, brother said malloc wouldn't be an issue for inefficiency. Maybe it's something else.
 
Ydahs said:
This is for C, but thought I'd ask it here since C++ is the closest thing to C

What's the most effective way to pair objects to use in a return function?

I have something similar to this (not the actual code):
Code:
pair(a,b)
{
	Obj* pair = malloc(sizeof(Obj*)*2);
	pair[0] = a;
	pair[1] = b;
	return list;
}
The issue here is that I need all the efficiency I can get for this and malloc is slowing things down. Obj* pair[2] causes a segfault.

edit: hmm, brother said malloc wouldn't be an issue for inefficiency. Maybe it's something else.

I'd rate that code as downright nasty. Are a & b pointers to objects, copies or references? You're just storing two pointers in pair, is that what you intended? Are you making sure to clean elsewhere this object you've allocated?

If you absolutely utterly need to store a & b in some sort of structure, just create your own Pair structure to contain them. That way you can just go new pair(a,b) & initialise it correctly etc, instead of relying on whatever code calls pair(a,b) to /know/ there's two elements to the array that's being returned.

Code:
struct Pair
{
      Pair(const Object * a, const Object * b)
      : m_a(a)
      , m_b(b)
      {
       }
      Object * m_a;
      Object * m_b;
};
etc.
 
fenners said:
I'd rate that code as downright nasty. Are a & b pointers to objects, copies or references? You're just storing two pointers in pair, is that what you intended? Are you making sure to clean elsewhere this object you've allocated?

If you absolutely utterly need to store a & b in some sort of structure, just create your own Pair structure to contain them. That way you can just go new pair(a,b) & initialise it correctly etc, instead of relying on whatever code calls pair(a,b) to /know/ there's two elements to the array that's being returned.

Code:
struct Pair
{
      Pair(const Object * a, const Object * b)
      : m_a(a)
      , m_b(b)
      {
       }
      Object * m_a;
      Object * m_b;
};
etc.
Yeah, sorry about the example being unclear. The actual code is pointers to the objects stored in the array. Pairing two objects is a requirement unfortunately.

I actually did create a pair struct (not defined like that), though it started to get a bit messy. Also, the syntax looks odd. Is that written in C++? I don't think I have enough time to implement this before the project deadline, but I'll still mess around with it and see if it helps.

Thanks for the help.
 
Zoe said:
Don't do that, post solutions!

Maybe it was embarrassing, like a misplaced semi-colon.
KuGsj.gif
 
Zoe said:
Don't do that, post solutions!

Haha, I'm sorry. :(

Well here's another question. :) Is there something wrong with the way I'm writing data to my output file?

Code:
	for(int i=0; i<5; i++)
	{
		.
		.
		.
		.
		cout<< customerName[i][0] << "  $" << customers.cost() << endl;

		ofstream billFile;
		billFile.open ("billing.dat");
		billFile << customerName[i][0] << "  $" << customers.cost() << endl;
		billFile.close();
	}

My cout is displaying it the way I want it:
http://i.imgur.com/DNYDC.png

However, my output file only has "Hansen $17.95" showing.
 
Heysoos said:
Haha, I'm sorry. :(

Well here's another question. :) Is there something wrong with the way I'm writing data to my output file?

Code:
	for(int i=0; i<5; i++)
	{
		.
		.
		.
		.
		cout<< customerName[i][0] << "  $" << customers.cost() << endl;

		ofstream billFile;
		billFile.open ("billing.dat");
		billFile << customerName[i][0] << "  $" << customers.cost() << endl;
		billFile.close();
	}

My cout is displaying it the way I want it:
http://i.imgur.com/DNYDC.png

However, my output file only has "Hansen $17.95" showing.

Yea. Each time you're opening the file, it destroys the old file. You should open it once before the loop and close after the loop.
 
I have a program I'd like to compile in release in Visual Studio.
When I choose "release" in the box on the top of my screen and run the solution, I get this message error:

"no debugging information. Debugging information for "mygame.exe" cannot be found or does not match. Binary was not built with debug information. "

Any idea what can I do?

It's almost my first time running something in release. I'm gonna ask just to be reassured: what I'd like to do is creat an .exe file for my game so I can launch it just by double clicking that .exe. Is compiling in release the way to do so?

Thanks! :)
 
FerranMG said:
I'm gonna bump this in case someone sees it in time for helping me before the evening.

Anytime you compile and link you will get an exe. It will be in the debug or release directory in your projects directory depending on the configuration that you built it with (debug build in debug directory, release build in release, etc.).

That message just means you won't be able to debug the project with symbols when running in release mode. That won't effect you unless youre trying to debug your release build.
 
Oh, alright then.
I recall looking for the .exe file yesterday, but it was late and I was very tired, so I might have overlooked it.
Plus, this error message I got made me think there was something wrong with the build.

I'm gonna give it a look later, thanks a lot for answering.
 
FerranMG said:
Oh, alright then.
I recall looking for the .exe file yesterday, but it was late and I was very tired, so I might have overlooked it.
Plus, this error message I got made me think there was something wrong with the build.

I'm gonna give it a look later, thanks a lot for answering.
The error message you're receiving is because you're trying to run it with debugging when you compiled without debugging enabled.

When you compile with debugging, the compiler disables code optimization and includes extra information about your function and variable names so that you can step through the code as you run it.

I'm not a Visual Studio guy, but I'm assuming that "compile for release" means to compile with optimization and without debugging.
 
Hello all. Im taking a C++ Object Oriented course and I am having a little trouble with this question:

Create a class that represents a length specified in inches or in inches and feet. The class will have the following features:
A constructor that takes the length in inches (e.g. 74 inches)
A constructor that takes the length in feet and inches (e.g. 6'4'')
Setters and getters for the length and height. See the driver for the prototypes.

Submitted Code Will Be Tested With The Following
#include <iostream>
#include "FeetInches.cpp"
using namespace std;

void doOutput(string name, FeetInches h)
{
cout << name << " is " << h.getFeetComponent() << "'" << h.getInchesComponent() << "\"" << endl;
}



int main()
{
cout << "-- Testing constructors --" << endl;
FeetInches h1(54);
FeetInches h2(7, 9);
doOutput("h1", h1);
doOutput("h2", h2);

cout << "-- Testing setLength --" << endl;
h1.setLength(2, 9);
h2.setLength(37);
doOutput("h1", h1);
doOutput("h2", h2);

h1.setLength(6, 4);
h2.setLength(76);
doOutput("h1", h1);
doOutput("h2", h2);

h1.setLength(6, 3);
h2.setLength(76);
doOutput("h1", h1);
doOutput("h2", h2);

h1.setLength(6, 5);
h2.setLength(76);
doOutput("h1", h1);
doOutput("h2", h2);
}

Program Output
-- Testing constructors --
h1 is 4'6"
h2 is 7'9"
-- Testing setLength --
h1 is 2'9"
h2 is 3'1"
h1 is 6'4"
h2 is 6'4"
h1 is 6'3"
h2 is 6'4"
h1 is 6'5"
h2 is 6'4"


Im not sure how to get the constructor to know if there is just one parameter, such as "FeetInches h1(54)" instead of of having two "FeetInches h2(7, 9)" , so I can then convert it to feet and inches.

Any help would be greatly appreciated. Thanks.
 
Yeah just overload constructor i first misread the assignment i thought you had to give a string("6'4\"") and then look at what was feets and what was inches.

But now just have a extra constructor that takes two int of floats.

like this
feetinches(float length)
feetinches(float feet,float inches)
 
Sorry for late response but thanks a bunch guys. Yea I just needed to brush up on how overloading the constructor worked and I got it. Thanks again.
 
I'm absolutely baffled as to why my code won't compile. The linking error description in VS is worthless.

StudentInfo.cpp
Code:
#include "StudentInfo.h"
#include "Stats.h"

using namespace std;

// default constructor
Student_info::Student_info() : midterm(0), final(0) { }


Student_info::Student_info(istream& is) { read(is); }


istream& Student_info::read(istream& in)
{
	in >> n >> midterm >> final;

	read_hw(in, homework);

	return in;

}


double Student_info::grade() const
{
	return ::grade(midterm, final, homework);
}


bool compare(const Student_info& x, const Student_info& y)
{
	return x.name() < y.name();
}


istream& read_hw(istream& in, vector<double>& hw)
{
	if (in)
	{
		// get rid of previous contents
		hw.clear();

		double x;
		while(in >> x)
		{
			hw.push_back(x);
		}

		// clear the stream so that input will work for the next student
		in.clear();
	}

	return in;
}


double grade(double midterm, double final, double homework)
{
	return 0.2 * midterm + 0.4 * final + 0.4 * homework;
}


double grade(double midterm, double final, const vector<double>& hw)
{
	if (hw.size() == 0)
	{
		throw domain_error("Student has done now homework");
	}

	return grade(midterm, final, median(hw));
}

StudentInfo.h
Code:
#ifndef STUDENTINFO_H
#define STUDENTINFO_H

#include <istream>
#include <string>
#include <vector>

class Student_info
{
public:
	Student_info();
	Student_info(std::istream&);

	std::string name() const { return n;}
	bool valid() const { return !homework.empty(); }

	std::istream& read(std::istream&);
	double grade() const;

private:
	std::string n;
	double midterm, final;
	std::vector<double> homework;

};


bool compare(const Student_info&, const Student_info&);


std::istream& read_hw(std::istream&, std::vector<double>&);


double grade(double, double, double);


double grade(double, double, const std::vector<double>&);



#endif

Stats.h
Code:
#ifndef STATS_H
#define STATS_H

#include <algorithm>
#include <vector>
#include <stdexcept>

template <class T>
T median (std::vector<T> v)
{
	typedef typename std::vector<T>::size_type vec_sz;

	vec_sz size = v.size();
	if (size == 0)
	{
		throw std::domain_error("median of an empty vector");
	}

	std::sort(v.begin(), v.end());

	vec_sz mid = size / 2;

	return size % 2 == 0 ? (v[mid] + v[mid - 1]) / 2 : v[mid];
}


#endif

Is it because I'm overloading the grade function?
 
It helps if you post the linker error. I'd suggest removing the template function and replacing it with a double version just to see if the issue is in there.
 
Lathentar said:
It helps if you post the linker error. I'd suggest removing the template function and replacing it with a double version just to see if the issue is in there.

Found it. The above code is correct. So apparently you get a link error if there isn't a main function in the code. Oh man what a silly mistake. It shows how used to I was to debugging in Java.
 
Yeah, I was about to post:

Is this the entire code? There needs to be a main function. Is your error "fatal error LNK1561: entry point must be defined"
 
Slavik81 said:
T median (std::vector<T> v) should be inline or you're going to get more linker errors down the road.

How do I do that? I thought templates had to be defined in their own header files.

Drkirby said:
Yeah, I was about to post:

Is this the entire code? There needs to be a main function. Is your error "fatal error LNK1561: entry point must be defined"

Yeah, that is the linker error I got.
 
Lasthope106 said:
How do I do that? I thought templates had to be defined in their own header files.
Code:
template <class T>
inline T median (std::vector<T> v)
{
	typedef typename std::vector<T>::size_type vec_sz;

	vec_sz size = v.size();
	if (size == 0)
	{
		throw std::domain_error("median of an empty vector");
	}

	std::sort(v.begin(), v.end());

	vec_sz mid = size / 2;

	return size % 2 == 0 ? (v[mid] + v[mid - 1]) / 2 : v[mid];
}

EDIT: Actually, it looks like the spec specifies that you have correct linkage in this case anyways. However, I would always mark an inline function as inline explicitly. That way you don't need to memorize corner cases like template function specializations.
 
I discovered my chdir call wasn't working, when it was working fine yesterday. I tried a bunch of things, and eventually found that if I called it again, it would work. Then, I tried commenting the first call out - it worked. When I commented the second call out, it didn't. I've established that it needs an extra line in the source to work - my source now looks like this:
Code:
    std::string path = argv[0]; // First string argument will (hopefully) contain the path to the executable
    int pos = path.find_last_of("/\\");
    path = path.substr(0, pos + 1); // Trim it up to and including the last / or \
    // This comment is necessary to get it to compile properly! Do not remove!
    chdir(path.c_str());
No idea what's going on here :P

Maybe it's my compiler trying to tell me to comment my code more!
 
I want to start over from the beginning and try to learn it all over again. I feel as if the classes I took didn't really help me all that much. What book or website should I use as learning tool?
 
Wichu said:
I discovered my chdir call wasn't working, when it was working fine yesterday. I tried a bunch of things, and eventually found that if I called it again, it would work. Then, I tried commenting the first call out - it worked. When I commented the second call out, it didn't. I've established that it needs an extra line in the source to work - my source now looks like this:
Code:
    std::string path = argv[0]; // First string argument will (hopefully) contain the path to the executable
    int pos = path.find_last_of("/\\");
    path = path.substr(0, pos + 1); // Trim it up to and including the last / or \
    // This comment is necessary to get it to compile properly! Do not remove!
    chdir(path.c_str());
No idea what's going on here :P

Maybe it's my compiler trying to tell me to comment my code more!

Try deleting that \ at the end of the previous line. That's a line continuation marker in C. I'm sure a language lawyer can come in and say how the standard treats \ at the end of a comment line, but in any case I almost guarantee that's your problem, whether it's a problem that's backed up by the C standard or just a bug in your compiler.
 
Status
Not open for further replies.
Top Bottom