Help combining two functions in C++ - c++

I need to combine these two functions.
and need help in so:
int Triangle(GzRender *render, int numParts, GzToken *nameList,GzPointer *valueList)
{
if (on_screen)
{
return Position(render, pos);
}
}
int Position(GzRender *render, GzCoord vertexList[3])
{
GzCoord *pv[3];
int i,j;
pv[0] = &vertexList[0];
pv[1] = &vertexList[1];
pv[2] = &vertexList[2];
//more function code in here
}
Can anyone help me with this.
Regards

Normally, separating out functions is a better, more common practice (and one of the main tasks during refactoring). That being said, you can "combine" these simply by doing:
int Triangle(GzRender *render, int numParts, GzToken *nameList,GzPointer *valueList)
{
if (on_screen)
{
//function code in here, working on "pos" instead of vertexList
// return value
}
// return some other value here?
}

The first poster (Reed Copsey) is correct about the fact that it's generally better to keep the functions separate.
Have you considered using the inline directive?
http://www.codersource.net/cpp_tutorial_inline_functions.html
Technically it's only a 'compiler hint' but you could try it. What it does is tell the compiler that you would like to include the body of the method denoted as inline in any other methods that call it. It's better from a maintenance standpoint, and should achieve what you are aiming for without the headaches of 'cut-and-paste' coding.
int Triangle(GzRender *render, int numParts, GzToken *nameList,GzPointer *valueList)
{
if (on_screen)
{
return Position(render, pos);
}
}
inline int Position(GzRender *render, GzCoord vertexList[3])
{
//function code in here
}

Flip them around if it isn't compiling. Put "Position" in front of "Triangle"

Related

Sorting a struct vector

I have a big problem..I'm beginner with programming and I try to make a program in C++ for a football league ranking which have to sort the teams depending on their points.
Can someone help with an idea, please?
I created a struct for the teams with the name and the number of points.
How can I sort the teams?P.S. Sorry for my bad English.
This is my code:
#include <iostream>
#include <algorithm>
using namespace std;
//I created a struct for the team.
struct team
{
char name;
int pct;
}v[20];
int main()
{ int i,sw,aux;
for(i=1;i<=4;i++)//read the names
{
cout<<"Team "<<i<<endl;
cin>>v[i].name;
}
for(i=1;i<=4;i++)//get the points
{
cout<<"Team "<<v[i].name<<" points"<<endl;
cin>>v[i].pct;
}
//bubble sort(not working)
do
{
sw=0;
for(i=1;i<=4;i++)
{
if(v[i].pct<v[i+1].pct)
aux=v[i].pct;
v[i].pct=v[i+1].pct;
v[i+1].pct=aux;
sw=1;
}
}while(sw==1);
for(i=1;i<=4;i++)
{
cout<<v[i].pct<<endl;
}
return 0;
}
You need to modify your sort part like this. Assuming you are sorting in desc order.
do
{
sw=0;
for(i=1;i<4;i++) //< not <= ,because in case of the last element you wont have any other element after it to compare
{
if(v[i].pct<v[i+1].pct) // use curly brace as you want all 4 following lines to be executed when its true
{
aux=v[i]; //swap entire struct not just one variable
v[i]=v[i+1];
v[i+1]=aux;
sw=1;
}
}
}while(sw==1);
Also you might need to edit variable type of team name as it can be string.
As you are using C++ there is a one liner function that you can use to sort
//#include<algorithm>
//define comparator function
bool cmp(team a, team b)
{
return a.pct < b.pct;
}
sort(v+1,v+4+1,cmp);
Also you can simply write the comparator inside the struct and then use the sort function:
struct team
{
char name;
int pct;
bool operator<(team other) const
{
return pct > other.pct;
}
}v[20];
sort(v+1,v+4+1);
I'm curious about why you include algorithm but do not use any of it. Do you know STL? Since you include algorithm, I guess you may know some simple functions such as swap, sort and copy. They are easy to use, you just need to type one line instead of writing a bubble sort by yourself. Before you use the sort function, you should define which order can take effect on these teams. Just like this:
bool compareTeams(const Team &t1, const Team &t2) {
if (t1.getScore() == t2.getScore()) {
return t1.getName() < t2.getName();
}
else {
return t1.getScore() < t2.getScore();
}
}
The code above defines a direction we consider to sort the teams, first we sort them by scores, if both of the scores are equal, then we sort them by their names.
Finally We can use the sort function which is ready-made in STL. Now the order we defined can be used. (I guess the array v[] stands for the teams. Am I right?)
std::sort(v, v + 20, compareTeams);

Returning vector from template function

Hoping for some clarification here. The code below executes fine, but when I uncomment that else statement a compilation error occurs. It's because in main I'm specifying a type int event though there's the possibility of type string. I've simplified my actual code to what's below to narrow down on the problem, what can I do to make it so that vector data in main can be of whatever type getNextLineOfData returns?
#include <vector>
using namespace std;
template< typename T>
std::vector<T> getNextLineOfData(bool someBoolean)
{
std::vector<T> data;
if (someBoolean)
{
data.push_back(1);
data.push_back(2);
data.push_back(3);
}
/*
else
{
data.push_back("1");
data.push_back("2");
data.push_back("3");
}
*/
return data;
};
int main()
{
vector<int> data = getNextLineOfData<int>(true);
return 0;
}
You are confusing compile time operations with runtime operations in your code snippet. When you template the function getNextLineOfData and instantiate it with getNextLineOfData<int>, the compiler goes ahead and generates a function that returns a vector for you. The if statement however is only evaluated at run time. So when the compiler tries to build your code it sees that you are adding both 1 and "1" to your vector<int> container based on the conditional. This is not allowed.
You could solve your problem with template specialization.
#include <vector>
using namespace std;
template<typename T>
std::vector<T> getNextLineOfData() {
// default
}
template<>
std::vector<int> getNextLineOfData()
{
std::vector<int> data;
data.push_back(1);
data.push_back(2);
data.push_back(3);
return data;
};
template<>
std::vector<std::string> getNextLineOfData()
{
std::vector<std::string> data;
data.push_back("1");
data.push_back("2");
data.push_back("3");
return data;
};
int main()
{
vector<int> data = getNextLineOfData<int>();
return 0;
}
EDIT: As #BobTFish points out, it might be better to overload the function rather than template specialize it. The solution above solves the problem the way you had it initially set up.
Reading from extra information in comments, I would suggest something like:
void getNextLine(std::vector<std::string>& output)
{
output.push_back("string data as you please");
}
void getNextLine(std::vector<int>& output)
{
output.push_back(1);
}
bool nextLineIsIntData()
{
// somehow determine if the coming data is strings or ints
return false;
}
int main()
{
std::vector<std::string> stringData;
std::vector<int> intData;
if (nextLineIsIntData())
getNextLine(intData);
else
getNextLine(stringData);
// do whatever you want
}
Well what you are doing is simply illegal. When you look at the if-else statement you say, well if some condition is true than this will execute but this won't, so it stands too reason that the compiler will ignore the part that is not executed. This is flat out wrong. What you need to do, which is layed out in previous answers is too overload or specialize the function for the different data types.
I should also mention that what you are trying to do is bad style. You are essentially relying on the user too pass the correct bool value, which influences the types you push_back() into the vector. Why do this when you have the power of template pattern matching at your disposal which completely removes the need to rely on correct user input.
In this case and any similar ones you come across it's much better to let the compiler decide

c++ Class Function return Struct element

so curiosity got me looking for an alternative method of returning specific data or part of a structure. I currently have a structure and class similar, if not exact to this:
struck Pos {
Int x_{0},
y_{0},
z_{0};
};
class Object {
private:
Pos xyz_{ 0, 0, 0 };
public:
const Pos getPos() { return xyz_; }
};
Now this is without constructors and stuff. Anyway the I'm trying/wanting to return the x_ of xyz_ now I could just do:
const int getPosX() { return xyz_.x_; }
but that seems impractical as I'd have to do that 3 times as well as modify my main code to compensate for the changes. So wondered if there's an easier or better method for doing something like:
Object ob; // Empty I know but you get the idea?
int xValue = ob.getPos.x_;
Any help is deeply appreciated.
ob.getPos().x_;
Worked, simply overlooked the ().

How to name a function and a variable with the same name?

The following code cannot be compiled by VC++ and clang.
int f()
{
return 0;
}
int main()
{
// error : called object type 'int' is not a function or function pointer
int f = f();
}
It is necessary in some cases. For example, I have a function to calculate the character count of a string, which is named count, however, another function parameter is also expressively named as count.
size_t count(char* sz)
{
return strlen(sz);
}
bool check_count(char* sz, size_t count)
{
return count == count(sz); // ???
}
How to resolve this issue?
In C++ you can define a namespace for your objects, in your example you could do:
namespace MyFunctions {
int f()
{
return 0;
}
}
int main()
{
int f = MyFunctions::f();
}
The answer is simple. This is not supported. C, as many other languages, cannot support absolutely every scenario. It is unreasonable to put out such a goal. Nobody ever tried to achieve this.
In your particular case, you should rename your parameter. Function always has limited scope. It is always recompiled as a whole. Names of params in prototypes in the header files may have different names. Renaming param in the body of the function will work in 99.9999% of cases.

What's the difference between declaring functions before or after main()?

What's the difference between:
void function();
int main()
{......}
void function()
{......}
vs
void function()
{.......}
int main();
It seems odd to declare a function before main then define it after main when you could just declare and define it before main. Is it for aesthetic purposes? My teacher writes functions like the first example.
It's just for code organization purposes ("aesthetics", I guess). Without forward declarations you'd need to write every function before it's used, but you may want to write the bodies of a function in a different order for organizational purposes.
Using forward declarations also allows you to give a list of the functions defined in a file at the very top, without having to dig down through the implementations.
Forward declarations would also be necessary in the case of mutually recursive functions. Consider this (silly) example:
bool is_odd(int); // neccesary
bool is_even(int x) {
if (x == 0) {
return true;
} else {
return is_odd(x - 1);
}
}
bool is_odd(int x) {
return is_even(x - 1);
}
Note I mean to make this answer supplementary, others have already given good answers to this questions.
Note that knowing how to forward declare things in C++ becomes very important. Once you begin using header files it basically becomes mandatory. Header files will allow you to build a prototype of functions and classes/structs then define them in a corresponding .cpp file. This is a very important organizational feature of C++.
// MyClass.h
class MyClass
{
public:
MyClass(int x);
void printInt();
private:
int myInt;
};
// MyClass.cpp
MyClass::MyClass(int x)
{
MyClass::myInt = x;
}
void MyClass::printInt()
{
std::cout << MyClass::myInt;
}
Doing things this way makes it so you're not completely bound to make a huge hodgepodge of code. Especially if you're writing real programs that will have a considerably large amount of source code.
So while in the question you asked forward declaring is really just more of a preference, later on it really won't be a choice.
Your first example is in the Top-Down style, the second in Bottom-Up style.
It's largely aesthetic, in that some people prefer one over the other.
For example, someone might prefer to get a high-level overview of the program before getting the details (top-down), while another might person might prefer to see the details first (bottom-up).
A tangible benefit of the declarations in the top-down approach is that you can more easily re-organize the function definitions without having to worry about ordering.
Look at this example:
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
where, int max(int num1, int num2) is behaving as a function.
Now, here we have a program
#include <iostream>
using namespace std;
// function declaration
int max(int num1, int num2);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int ret;
// calling a function to get max value.
ret = max(a, b);
cout << "Max value is : " << ret << endl;
return 0;
}
// function returning the max between two numbers
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
I kept max() function along with main() function and compiled the source code. While running final executable, it would produce the following result:
Max value is : 200
Calling a Function:
While creating a C++ function, you give a definition of what the function has to do. To use a function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value.