Change given function parameter within the function c++ - c++

I wrote an function called swap to swap given two elements within the function. But when I use it in another function, it doesn't work. How to get it work?
#include <iostream>
using namespace std;
void swap(int *a, int * b){
int temp=*a;
*a=*b;
*b=temp;
}
void sum(int x, int y){
int *a;
a = &x;
int *b;
b=&x;
swap(a,b);
//cout << x << endl << y << endl;
}
int main(){
int a=0, b=1;
//swap(a,b);
sum(a,b);
cout << a << endl << b << endl;
return 0;
}

b=&x;
should be
b=&y;
Also, you are swapping local copies. sum should be:
void sum(int& x, int& y)
Also, this already exists. It's called std::iter_swap.

You probem not in swap, but in sum function, you pass x an y by value and modify and swap copyies of values later to fix this you need to change void sum(int x, int y){ to void sum(int& x, int& y){ this will leads to x and y being passed by reference so that sum will be able to update them.

I guess by 'wrong' you mean the output of the last cout doesn't show 'a' and 'b' as you'd expect. But you're passing them to 'sum' by value.

I assume you are just learning about pointers and references.
Your function swap swaps the contents of two pointers. Note that you have put in using namespace std and std also has a swap function so I would suggest removing that from your source, albeit yours will be a closer match if you pass in pointers to ints.
Your function called sum is a clear misnomer as it doesn't actually sum or add anything, it tries to do a swap by calling the pointer version.
To fix your particular bug, it would have to take its parametesr by reference, and b should point to y, not x.

x and y are passed by value to sum so swap is working on a local copy not the actual variables from main. You will also need to modify sum and your call to swap:
void sum(int &x, int &y)
^ ^
{
// other code
swap(&x,&y);
^ ^
}
If you leave you call to swap like this:
swap(x,y);
you will actually call std::swap. I am going to assume you will be adding more code to sum otherwise the name is not consistent with what it does.

Related

how to swap 2 variables using recursion

i've tried to swap 2 variables using recursion.So i passed them by reference and nothing change in the main frame. But inside the function scope it works...Can anyone explain me how this code works inside the stack and if is there any other solution to swap varibles using recursion?
#include <iostream>
void swap(int &a, int &b) {
if (a>b)
{
swap(b,a);
}
}
int main()
{
int x = 10;
int y = 8;;
swap(x, y);
std::cout << x << ' ' << y;
return 0;
}
Simply switching the parameters in the recursive call doesn't actually swap the values of the variables in the caller, or anywhere else. There's no (sensible) way to write this recursively because swapping isn't a recursive procedure. Recursion is used when you're traversing a data structure with multiple elements, like an array or a tree, or you're manipulating numbers repeatedly over time, as in a Fibonacci sequence.
But here, there's no repeated decision to be had. All it is is "swap if a > b, otherwise don't", which is a simple if, plus one of the normal swapping approaches you described:
#include <iostream>
void swap_if_greater(int &a, int &b) {
if (a > b) {
std::swap(a, b);
}
}
int main() {
int x = 10;
int y = 8;
swap_if_greater(x, y);
std::cout << x << ' ' << y; // => 8 10
}
Note that I've renamed the function. swap implies an unconditional swap, but that's not what the function does. The function ensures the lower value will be in the first argument, so it's been renamed to swap_if_greater to reflect that. If you do want an unconditional swap, use std::swap.

How to use c++ swap function?

When I write like this swap(a,b); it is ok.
When I write like this swap(&c[0],&d[0]); there is a error.
Somebody can tell me why?
#include<iostream>
#include<algorithm>
using namespace std;
int main(void){
int *a;
int *b;
int c[]={1,2};
int d[]={3,4};
a=&c[0];
b=&d[0];
swap(a,b);// it is ok
//swap(&c[0],&d[0]);// it is error why
cout<<a[0]<<" "<<b[0]<<endl;
cin.get();
}
user3365922 is correct on the syntax if you wish to swap the contents of c[0] and d[0].
Just to add on because you code sample is a bit weird.
std::swap(a,b) in your code isn't actually swapping the contents c[0] and d[0]. It's swapping the pointers a & b. I mention this because it looks like you replaced the std::swap(&c[0], &d[0]) with std::swap(a,b)--which isn't actually equivalent (this is an assumption, my bad if they weren't meant to be equivalent).
I'm not totally sure what your goal is, but std::swap(c[0], d[0]) will achieve swapping the first entry of c with the first entry of d (leaving the second entry as-is). If you actually wanted to swap the contents of arrays entirely in the example above, you could also do std::swap(c, d).
Replace swap(&c[0],&d[0]) with swap(c[0], d[0]).
&c[0] and &d[0] are rvalues (temporary objects of type int*), but you can swap lvalues only.
You're able to swap(a, b) because a and b are lvalues, a after swap will be pointing to d[0] and b to c[0], swap(a, b) wouldn't swap values in array, this is a difference in behaviour (thanks to M.M's comment with a notice).
swap function
template <class T> void swap ( T& a, T& b )
{
T c(a); a=b; b=c;
}
And a=&c[0]; b=&d[0]; after swap(a,b);
a will pointing to d[0]
b will pointing to c[0]
and here swap(&c[0],&d[0]); the prototype dose not match the current swap function.The required prototype is
swap(int*,int*)
so there is no matching function to call so the compiler throws error.
The arguments to std::swap() are two integer pointers, not two addresses of an array with an index.
For swapping normal singular int values you will have to use a pointer (call by reference), but for an array you could directly pass it (as base address of array is taken) for which you could have used c[0],d[0]. Using & to reference the array (i.e. using &c[0],&d[0]) with the function accepting a int * type would cause argument type mismatch, with your passed values being rvalues of type int *, which cannot be swapped. (whereas lvalues like c,d and c[index],d[index] can be swapped)
The error you recieved should be:
main.cpp:12:13: error: no matching function for call to ‘swap(int*, int*)’
swap(&c[0],&d[0]);
^
This pertains to invalid initialization of a non-const reference of type int*& from an rvalue of type int*, which is included in the error message.
If what you want to consider as the parameters are indeed addresses of the arrays, this would be your function:
void swap_array_elements(int a, int b, int arr[], int arr2[])
{
int temp = arr[a];
arr[a] = arr2[b];
arr2[b] = temp;
}
Note that the first two arguments used here are indices of the two arrays passed respectively as the third and fourth argument. This will swap in between any two elements you require among the two arrays.
Example:
#include <iostream>
void swap_array_elements(int a, int b, int arr[], int arr2[])
{
int temp = arr[a];
arr[a] = arr2[b];
arr2[b] = temp;
}
int main()
{ int array1[]={42,56}, array2[]={63,89};
swap_array_elements(0,1,array1,array2); // swapping element with index 0 in array1 (42) with element with index 1 in array2 (89)
std::cout<<array1[0]<<" "<<array2[1]; // 89 42
return 0;
}

How to use an array of pointers to functions?

I want to use for example this array of pointers to functions, without using STL.
That array is an array of pointers that I call functions OptionA, OptionB and so on.
int(*Functions[4])();
Functions[0] = OpionA;
Functions[1] = OptionB;
Functions[2] = OptionC;
Functions[0] = Exit;
Now if I write inside the function where I have my array
Functions[0];
I want to have called function 'OptionA' where it has been defined before for example like this:
int OptionA()
{
cout << "OPTION A";
_getch();
return 0;
}
Is it possible to do this without STL?
If not, I would like to know how to do it with STL.
You can create and pass arrays of function pointers like any other types. It's easiest if you have a type alias (my example leverages using, but typedef will also work).
#include <iostream>
using Function = int (*)(int, int);
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
void do_stuff(int a, int b, Function * fns, int cnt) {
for(auto i = 0; i < cnt; ++i) {
std::cout << "Result " << i << " = " << fns[i](a, b) << '\n';
}
}
int main() {
Function fns[2] = { add, sub };
do_stuff(10, 7, fns, 2);
return 0;
}
Output:
Result 0 = 17
Result 1 = 3
I think that what you are looking for is
How to initialize a vector of pointers
Once your vector is initialize you can send it to a function like a normal data type.
Example:
std::vector<int*> array_of_pointers{ new int(0), new int(1), new int(17) };
function(array_of_pointers);
In the declaration of the function
void function(std::vector<int*> array_of_pointers);
I hope this answer your question.
In C and C++, arrays are second-class. They cannot be passed by value by themselves, only if somehow wrapped.
As a first step, the questions you have to decide are:
Does your array have a fixed length?
And do you have to pass it by value or can you pass it by reference?
If you have to pass it by value, is that a choice you want the caller to make, or the callee to impose? In the first case, pass it by reference.
If you pass the array by reference, nothing can beat using a gsl::span, unless you pass multiple sequences all having intrinsically the same length, in which case passing pointers and a single length-argument is more efficient and maybe comfortable.
If you pass an array of variable length by value, try to use a std::vector. That's also the go-to type to pass a by-ref argument as if by-value.
Otherwise (array of fixed length, by value), nothing beats std::array.
If p is a pointer to a function, which receives no parameters, you should call it by this syntax:
p();
So, if array is an array of pointers to functions, you should call one of them using the same syntax idea:
array[0]();
Here the parentheses are important; they say "call this function, and pass no parameters to it". If you have no parentheses
array[0];
this means "select this function from the array, but do nothing with it".
It's a useless expression, like if you have an integer x, then x * 5 means "multiply x by 5 and do nothing with the result" (useless), while x *= 5 means "multiply x by 5 and replace x with the result".

Why won't my values swap?

I am supposed to write a function name double_swap that takes two doubles as arguments and interchanges the values that are stored in those arguments. The function should return no value, so I know that means it must be a void function.
For example, if the following code fragment is executed,
int main()
{
double x = 4.8, y = 0.7;
double_swap(x,y);
cout<<"x = "<<x<<" y = "<<y;
}
The output will be:
x = 0.7 y = 4.8
The program I wrote is not swapping the values. I'd greatly appreciate if someone could point out my errors.
#include <iostream>
using namespace std;
void double_swap(double x, double y)
{
x = 1.9;
y = 4.2;
}
int main()
{
double x = 4.2, y = 1.9;
double_swap(x,y);
cout<<"x = "<<x<<" y = "<<y<<endl;
return 0;
}
You need to pass the variables by reference in order for the modifications in the function to apply to the variables from the call site. As it is right now all you are doing is modifying copies that get destroyed once the function ends.
Change
void double_swap(double x, double y)
to
void double_swap(double& x, double& y)
Also instead of hard coding the values lets do a real swap using
void double_swap(double& x, double& y)
{
double temp = x;
x = y;
y = temp;
}
You could also use pointers for the function paramters for this but then your call site would have to be changed to double_swap(&x,&y); and you would have to remember to reference the pointers in the function.
Instead of doing all of this though we can just use std::swap and let it do this for us.
When calling a function in c++ , There is 3 way to pass the parameters. The first one is by Copy where it only make a copy of the variable in parameters and then delete them.
void double_swap(double x, double y)
The second one is by Reference, where the paramaters refere to the real variable (Whats you want).
void double_swap(double& x, double& y)
And the last one is by address where you pass the address of the variables.
void double_swap(double* x, double* y)

Guidance with using classes/constructors

I am writing a program that asks the user for two vectors (with a force and magnitude) and then returns the sum of the two vectors. I'm not really looking for someone to just give me the code, but I really just need some guidance on how to proceed. I feel like I really don't understand the implementation of classes/constructors yet and so I'm pretty sure I'm doing things incorrectly, or at least inefficiently. NOTE: I hope it's obvious I'm not finished. I'm just having kind of a "coder's block" :P
#include "std_lib_facilities_4.h"
class Physics_vector {
double force, magnitude, x, y, f, m;
vector<double> final;
vector<double> v;
public:
Physics_vector(double x, double y) :force(x), magnitude(y) {};
void set_vector(double f, double m);
int get_vector(vector<double> final);
double add_physics_vector();
};
void Physics_vector::set_vector(double f, double m)
{
f = force;
m = magnitude;
vector<double> final;
final.push_back(f);
final.push_back(m);
}
int Physics_vector::get_vector(vector<double> final)
{
for (int i = 0; i < 2; ++i) {
cout << final[i] << '\n';
}
return 0;
}
int main()
{
cout << "Howdy!" << '\n';
cout << "This program adds together two vectors."
<< endl;
cout << "First, enter in the force and magnitude of your first vector."
<< "\nExample: 4 7." << endl;
double user_force, user_magnitude, force, magnitude;
cin >> user_force >> user_magnitude;
Physics_vector first(user_force, user_magnitude);
first.set_vector(force, magnitude);
cout << "Next, enter in the force and magnitude of your second vector."
<< endl;
cin >> user_force >> user_magnitude;
Physics_vector second(user_force, user_magnitude);
}
EDIT: Ok, so I changed my code a little to make it cleaner (if it's not tell me). But now my problem is function calls.
class Physics_vector {
public:
Physics_vector(double x = 0, double y = 0) :x(x), y(y) {}
double get_vector(double x, double y);
private:
double x, y;
};
double Physics_vector::get_vector(double x, double y)
{
return x;
return y;
}
double add_physics_vector(vector<double> vect_1, vector<double> vect_2)
{
return 0.0;
}
int main()
{
cout << "Howdy! Please enter your first vector (direction and magnitude) ."
<< "\nExample: 1 2." << endl;
double user_direction = 0;
double user_magnitude = 0;
cin >> user_direction >> user_magnitude;
Physics_vector(user_direction, user_magnitude);
//get_vector(...aaaand I'm stuck...
}
How do I get get_vector(double x, double y) to use the x and y values from Physics_vector() as it's arguments? I'm sure this seems so rudimentary to most of you; I hate that I'm having so much trouble with classes...
Thanks in advance.
Generally, classes are used to represent a single unit of data--in your case, a vector (in the physics sense). The class itself should ideally contain only the member variables it needs to hold the data it represents and (only if absolutely necessary) any other pieces of data its member functions require to work. It appears you are trying to implement a vector that has two dimensions, so we'll start from there.
First, we need to determine the minimum required member data the class needs to perform its function. I find that thinking too hard about this does nothing but make the class overly complicated. In physics, a vector in two dimensions can be represented in multiple ways, but the most common is the Cartesian form (x, y). So, in order to implement this all that is required are those two variables. All other information about the vector can be calculated from those two numbers. To begin the declaration of the class:
class Physics_vector {
double x, y;
public:
// Constructors and member functions here...
...
You seem to have the constructor down: all it needs to do is initialize those two variables. However, we can add some additional functionality: what if we wanted to declare a Physics_vector without actually giving it a value yet? Well, then we could code the constructor to give x and y some reasonable default values when it's constructed without any values:
...
explicit Physics_vector(double x = 0, double y = 0):x(x), y(y) {}
...
The explicit keyword is to make sure that the constructor must be called explicitly, because in C++ a constructor that may take one argument also defines an implicit conversion from that argument to the class's type, and Physics_vector vec = 0; isn't a sensible conversion. Next, we'll need some way to access x and y from outside the class, so we'll make some getter and setter functions that access the two values:
...
double get_x() const {
return x;
}
double get_y() const {
return y;
}
void set_x(double x) {
this->x = x;
}
void set_y(double y) {
this->y = y;
}
...
Think of the const keyword as a promise you're making to the compiler that the member function won't modify any of the member variables. You may remove it and the class will still work, but it's usually best to put it in when it makes sense.
The syntax this->x = x; is necessary because x is declared twice in the scope of setter member functions: once in the function's arguments, and once in the classes member variables. The compiler isn't able to tell which is being referred to, so the C++ standard defines that the local declaration takes precedence. Therefore, trying to write x = x; will assign the function's argument x to itself. I noticed you did this by accident in your set_vector function (you assigned the member variable force to the function argument f, and the same thing for m and magnitude, and I don't think that's what you intended). The way to get around it is to use the this pointer (which is defined in member functions, constructors, and destructors, and always points to the current instance of the class).
Next, we'll define an add function, because it's sensible to code the addition of two Physics_vectors with the class. The function should take another Physics_vector and add it to *this, and return the result.
...
Physics_vector add(Physics_vector other) const {
return Physics_vector(x + other.x, y + other.y);
}
...
Although this next part is more advanced (and may not have been covered in your class yet), I'll put it out there anyway. What if we wanted to add two Physics_vectors like we would two doubles? In other words add Physics_vectors vec1 and vec2 like Physics_vector result = vec1 + vec2;. Well, C++ provides a way to define such an operation. We would code it like this:
...
Physics_vector operator + (Physics_vector other) const {
return Physics_vector(x + other.x, y + other.y);
}
...
We can also add some other useful functions, such as a function that returns the magnitude of the Physics_vector.
...
double magnitude() const {
return sqrt(x*x + y*y);
}
}; // End of the the declaration/definition of Physics_vector.
The sqrt function is defined in the header cmath, and computes the square root of its argument. The magical std_lib_facilities_4.h header you're including (probably created by your instructor for your convenience) may or may not have included cmath for you.
Given this class you can then implement your program like this:
int main()
{
double x1, y1, x2, y2;
cout << "Please give two vectors to add.\n";
cout << "x1: ";
cin >> x1;
cout << "\ny1: ";
cin >> y1;
cout << "\nx2: ";
cin >> x2;
cout << "\ny2: ";
cin >> y2;
Physics_vector vec1(x1, y1);
Physics_vector vec2(x2, y2);
Physics_vector result = vec1.add(vec2); // Or vec1 + vec2, if you use the operator + overload I described.
cout << "\n\nvec1 + vec2 = ("
<< result.get_x() << ", "
<< result.get_y() << ")";
}
Hope that helps you with your programmer's block!
It looks like you should probably improve your understanding of C++ classes in general. Here is a good place to start. I'll try to give you a few pointers though.
Assuming your vector class only needs to store two values you have
way to many member variables. You actually only need two doubles:
force and magnitude (do you mean magnitude and direction?). The
variables of type vector are unnecessary, as despite its name, an
std::vector is only a dynamic array.
You don't need a separate set_vector() method as you are already
setting the values for your vector in the constructor by passing
force and magnitude values in there. On the other hand you may want
to add accessors for the member variables as get_force() and
get_magnitude() as well as perhaps set_force() and
set_magnitude() if you think you may want to change these values
from outside.
For adding the vectors you should use operator overloading and
implement a method called operator+ which will let you you easily
add two vectors together by simply typing something like v3 = v1 + v2.
This is mostly a matter of style and its not necessary, but I'd
suggest you to add some kind of prefix to your member variables, so
they are easily distinguished from local variables in the code. A
popular convention is to use m_variable. Also listing your public
members first, generally makes class interface slightly easier to
read.
With all the above in mind your vector interface could look like this (I'll leave the implementation to you):
class PhysicsVector
{
public:
PhysicsVector(double force, double magnitude) : m_force(force), m_magnitude(magnitude)
{
}
double getForce() const;
double getMagnitude() const;
void setForce(double force);
void setMagnitude(double magnitude);
PhysicsVector operator+(PhysicsVector other) const;
private:
double m_force, m_magnitude;
}
If you're getting the effect you want, you're doing things fine. However I'm not really sure if that's the case. As far as I know, a vector in physics is a body having magnitude and direction.
If you're trying to design a simple Physics_vector class, I would probably stick with:
class Physics_vector{
double x, y;
public:
Physics_vector(double x, double y);
};
Or, in case you want to operate in N-dimensional space:
class Physics_vector{
unsigned int dimensions; // Optional, same as magnitudes.size();
vector<double> magnitudes;
public:
Physics_vector(unsigned int dimensions, ...);
}
Or, in the last case - simply use templates (possibly variadic if you're operating in C++11).