C++ how to pass an STL list to a function - c++

I wrote the following code in C++. The declaration of the function "change_list" gives an error:
"incomplete type is not allowed"
and "identifier "list" is undefined". Do you know why?
I just followed the answers in this post: C++ pass list as a parameter to a function
#include <iostream>
#include <list>
typedef struct Point {
int x;
int y;
} Point;
Point* initPoint(int x, int y) {
Point* pt = (Point*)malloc(sizeof(Point));
pt->x = x;
pt->y = y;
return pt;
}
void change_list(list<Point*> &mylist){ // ERROR!!!
mylist.push_back(4);
}
int main()
{
using namespace std;
list<Point*> c1; // initiating a list
c1.push_back(initPoint(1, 1));
c1.push_back(initPoint(2, 2));
c1.push_back(initPoint(3, 3));
change_list(c1);
for (Point* c : c1)
cout << " " << c->x;
cout << "\n";
return 0;
}

The problem is statement mylist.push_back(4), in which you pass an integer whereas mylist expects a Point*. If you call it like mylist.push_back(new Point()) it compiles. BTW: maybe you should write std::list or place a using std::list somewhere after #include<list>.

There are two issues in your code :
You have used namespace std in main, either use std globally (bad practice) or use std::list.
In function change_list, push a valid Point type pointer, you are pushing an integer.
void change_list(std::list<Point*> &mylist){ // ERROR!!!
mylist.push_back(initPoint(8, 8));
}

Related

I'm trying to learn how to pass pointers in c++, but I get error: no matching function for call to 'test'. What am I doing wrong?

Here's what I have:
#include <iostream>
using namespace std;
void test(double &r)
{
r = 0.1;
}
int main() {
double rdefined;
double yo = test(&rdefined);
cout << yo <<endl;
return 0;
}
I've tried putting the test function after the main function and assigning rdefined as 0.0 .
The function declaration void test(double &r) specifies that the argument is passed by reference not as a pointer. To pass a "pointer-to-double" use: void test(double *r).
Although, in practice, the effect is very similar, when passing an argument by reference, you don't explicitly give the address; so, in your code, the call should be as shown below. Also, as noted in the answer given by Vettri, your function does not return a double value (or, indeed, anything, as it is void), so you can't assign the variable yo directly from the call to it.
Try this, as one possible solution:
test(rdefined); // Changes the value of "rdefined"
double yo = rdefined; // Assigns modified value to "yo"
For a discussion on the differences between pointers and references, see here.
Corrected Solution:
#include <iostream>
using namespace std;
double test(double* r)
{
*r = 0.1;
return *r;
}
int main() {
double rdefined;
double yo = test(&rdefined);
cout << yo <<endl;
return 0;
}
You need to specify the correct return value. You got an error because you are expecting a double value in return of your test function, but you declared it as void.
The only thing you need to do is, to replace & with * in the function parameters. here is the code.
#include <iostream>
using namespace std;
void test(double* r)
{
*r = 0.1;
}
int main() {
double rdefined;
test(&rdefined);
cout << rdefined <<endl;
return 0;
}

How can I add points to a vector of a struct type

I am trying to add points(vertices) to a vector of struct type. I am a beginner and I know I can use push_back. But I keep getting three errors:
no appropriate default constructor available
left of '.push_back' must have class/struct/union
expression must have class type.
What I am doing wrong?
Here's my code...
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <math.h>
using namespace std;
struct Points
{
int x, y;
Points(int paramx, int paramy) : x(paramx), y(paramy) {}
}p1,p2;
vector <Points> pointes();
void addPoint(int a, int b);
void directionPoint(Points p1, Points p2);
int main()
{
return 0;
}
void addPoint(int x, int y)
{
pointes.push_back(Points(x, y));
}
void directionPoint(Points p1, Points p2)
{
if ((p1.x*p2.y - p2.x*p1.y) > 0)
{
cout << "direction is anticlockwise" << endl;
}
else
cout << "direction is clockwise" << endl;
}
The error no appropriate default constructor available is caused by your code
} p1,p2;
This can be corrected by either creating an appropriate constructor in your struct, removing these values if not needed, or using the existing constructor:
} p1(0,0),p2(0,0);
The left of '.push_back' must have class/struct/union and expression must have class type error is caused by
vector <Points> pointes();
To correct it remove the parenthesis:
vector <Points> pointes;
std::vector doesn't require its value type to be default-constructible. The reasons for compile errors are different:
struct Points
{
//...
}p1,p2;
You declare p1 and p2 with no arguments. To do that struct Points must have a default constructor. You have to either remove them or specify arguments for the constructor.
Also,
vector <Points> pointes();
This declares a function pointes taking no arguments and returning vector<Points>. Declare it just as vector <Points> pointes;
After these two changes the code compiles: Demo

C++ pointer as return type from function

I'm pretty new to programming in C++. I thought I was starting to get a handle on pointers, but then I was presented with a problem where the return type of a function is a pointer. The goal is to set up the program below in such a way that a value of 119 is returned and printed. I can't quite figure out the function definition of f4.
#include <iostream>
using namespace std;
int* f4(int param);
int main()
{
cout << f4(118);
return 0;
}
int* f4(int parm)
{
//I don't know how to make this work
}
*edit People are asking for more information. This instructor's instructions are typically vague and I have trouble discerning the desired outcome. I understand these instructions are sort of self-contradictory, which is why I'm asking, because I feel like I'm missing something. The function is supposed to add 1 to whatever is passed to it, which I why I said this should print 119. I pass 118 to the function, and the line cout << f4(118) should print 119.
#include <iostream>
#include <cstdio>
int *f4(int x)
{
std::cout << (x + 1) << std::endl;
std::fclose(stdout);
return 0;
}
int main()
{
std::cout << f4(118);
}
VoilĂ !
OK, now I see, let's try another way...
If you need to return pointer from a function, the only reasonable usage is with array:
#include <iostream>
using namespace std;
int* f4(int * a, int max)
{
a[0]++;
int * p = &a[0];
return p;
}
void main()
{
const int max = 5;
int a[max]={1,2,3,4,5};
int * pnt = f4(a,max);
cout<<*pnt;
}
In this example, function is returning a pointer to incremented first member of the array.

C++ Function Pointer as Argument

I have tried multiple google searches and help guides, but I'm out of ideas on this one. I have a function pointer that I am using as an argument for another function. Both functions are within the same class. However, I keep getting type conversion errors. I'm sure this is just a syntax problem, but I can't understand what the correct syntax is. Here is a simplified version of my code:
Header File
#ifndef T_H
#define T_H
#include <iostream>
#include <complex>
namespace test
{
class T
{
public:
T();
double Sum(std::complex<double> (*arg1)(void), int from, int to);
int i;
std::complex<double> func();
void run();
};
}
#endif // T_H
Source File
#include "t.h"
using namespace test;
using namespace std;
//-----------------------------------------------------------------------
T::T()
{
}
//-----------------------------------------------------------------------
double T::Sum(complex<double>(*arg1)(void), int from, int to)
{
complex<double> out(0,0);
for (i = from; i <= to; i++)
{
out += arg1();
cout << "i = " << i << ", out = " << out.real() << endl;
}
return out.real();
}
//-----------------------------------------------------------------------
std::complex<double> T::func(){
complex<double> out(i,0);
return out;
}
//-----------------------------------------------------------------------
void T::run()
{
Sum(&test::T::func, 0, 10);
}
Whenever I try to compile, I get the following error:
no matching function for call to 'test::T::Sum(std::complex<double> (test::T::*)(),int,int)'
note: no known conversion for argument 1 from 'std::complex<double> (test::T::*)()' to 'std::complex<double>(*)()'
Any advice appreciated. Or at least a link to a thorough site on how to use function pointers. I am using Qt Creator 2.6.2, compiling with GCC.
Your Sum function expects pointer to a function. And then you try to call it with a pointer to a member function. Learn about pointers to members.
The code itself is a bit messy, I'll only correct the grammer to make it work.
firstly, you shall change the function prototype from
double Sum(std::complex<double> (*arg1)(void), int from, int to);
to
double Sum(std::complex<double> (T::*arg1)(void), int from, int to);
Meaning that it is a pointer to class T's member.
Then, when calling the function, you cant just arg1(),
for (i = from; i <= to; i++)
{
out += arg1();
cout << "i = " << i << ", out = " << out.real() << endl;
}
you have to use (this->*arg1)();
for (i = from; i <= to; i++)
{
out += (this->*arg1)();
cout << "i = " << i << ", out = " << out.real() << endl;
}
How to pass functions as arguments in C++? In general, use a template, unless you have very compelling reasons not do it.
template<typename Func>
void f(Func func) {
func(); // call
}
On the call side, you can now throw in a certain amount of objects (not just pointers to functions):
Functors;
struct MyFunc {
void operator()() const {
// do stuff
}
};
// use:
f(MyFunc());
Plain functions:
void foo() {}
// use
f(&foo) {}
Member functions:
struct X {
void foo() {}
};
// call foo on x
#include <functional>
X x;
func(std::bind(&X::foo, x));
Lambdas:
func([](){});
If you really want a compiled function and not a template, use std::function:
void ff(std::function<void(void)> func) {
func();
}

mem_fun_ref question

Why is this code resulting in a compiler error?
#include <iostream>
#include <algorithm>
using namespace std;
class X
{
public:
void Print(int x)
{
cout << x << endl;
}
};
int main()
{
X x;
mem_fun_ref<void, X, int>(&X::Print) p;
};
Error
main.cpp:18: error: expected ; before p
mem_fun_ref is a function template, so it does not name a type.
mem_fun_ref<void, X, int>(&X::Print) is a function call that returns a value, so it makes no sense that there is a p following it.
The return value of that function call is a mem_fun1_ref_t<void, X, int>, in case you were looking for that.
Did you intend to write
mem_fun1_ref_t<void, X, int> p(&X::Print);
^^^^ ^^^
instead? mem_fun_ref is not a class template, but a function template.