I need to swap a couple of integers in the format int i[2] using a void swap(int& x) function. As you see the function takes an argument of type int&. Here is non-working version of the function:
int i[2] = {3, 7};
void swap (int& x)
{
int temp;
temp = x[1];
x[1] = x[0];
x[0] = temp;
}
int main()
{
cout << i[0] << ", " << i[1] << "\n"; // return the original: (3, 7)
swap(i);
cout << i[0] << ", " << i[1] << "\n"; // return i swapped: (7, 3)
}
How should I do this?
Edit: The answer CANNOT use anything else for the function parameter. It MUST use a int& parameter. This is a problem from Bjarne Stroustrup's book: "The C++ programming language", third edition. It is problem #4 from chapter 5. The problem first asks to write a function taking a int* as parameter, than to modify it to accept a int& as parameter.
A reference isn't a pointer. I'd recommend changing the function signature if you can, but if you're stuck with it, you could do something like:
int *xx = &x;
int temp = xx[1];
xx[1] = xx[0];
xx[0] = temp;
That said, you should probably just use std::swap instead.
Looking at my copy, the exercise doesn't say how swap() should look like. It just says that it "swaps (exchanges the value of) two integers" and should take a) int* b) int& as the argument type.
As you tagged the question learning, the real question becomes:
Why does your swap() only take one argument?
All right, thanks to #gf's suggestions, I found a solution :) Many thanks! Please tell me if you see anything not very C++ish in there.
// Swap integers
#include<iostream>
using namespace std;
int i = 3;
int j = 7;
void swap (int& x, int& y)
{
int temp = x;
x = y;
y = temp;
}
int main()
{
cout << i << ", " << j << "\n"; // return the original: (3, 7)
swap(i, j);
cout << i << ", " << j << "\n"; // return i swapped: (7, 3)
}
Related
I need to print an array by implementing the use of a function before the main function. So I tried the following function:
int* printArr(int* arr)
{
for (int i = 0; i < 5; i++) {
cout << arr[i];
}
return arr;
}
I encountered two problems when implementing this into the whole code.
First, this is printing what I think is the address of the array and not the actual array. Pretty sure this is because of the return arr; in line 10. But if I do not write return then the code will produce an error. How can I fix this?
Second, I do not understand the second argument printArr has. In line 19, you can see cout << printArr(arr, 5) << endl;. How come there is a single numeric value, that one being 5 in this case, as an argument? How can I account for this in my function?
Please keep in mind that I am new to C++ and coding in general. Also, this code was given to me, hence why I do not understand certain aspects of it.
This is my code so you can see what I mean:
#include <iostream>
using namespace std;
// Declare function printArr here
int* printArr(int* arr)
{
for (int i = 0; i < 5; i++)
{cout << arr[i];}
return arr;
}
int main()
{
int arr[5] = {1, 3, 5, 7,9};
int last_num = arr[sizeof(arr)/sizeof(int)-1];
cout << "Before reversing" << endl;
cout << printArr(arr, 5) << endl;
// reverse "arr" using reference(&)
cout << "After reversing" << endl;
printArr(arr, 5);
return 0;
}
The declaration and implementation of printArr() is all wrong.
First, this is printing what I think is the address of the array and not the actual array.
The printArr() function itself is printing the contents of the array (well, the first 5 elements anyway), and then returning the address of the array. It is main() that is printing that address afterwards, when it passes the return value of printArr() to std::cout <<.
Pretty sure this is because of the return arr; in line 10. But if I do not write return then the code will produce an error. How can I fix this?
By getting rid of the return type altogether. There is no good reason to return the array pointer at all in this example, let alone to pass that pointer to std::cout. So printArr() should be returning void, ie nothing.
Second, I do not understand the second argument printArr has. In line 19, you can see cout << printArr(arr, 5) << endl;. How come there is a single numeric value, that one being 5 in this case, as an argument?
Because main() is passing in the element count of the array (5) so that printArr() can know how many elements to actually print, instead of hard-coding that value in the loop. However, your declaration of printArr() does not have a 2nd parameter with which to accept that value, that is why you are getting errors.
How can I account for this in my function?
By adding a 2nd parameter in the function declaration, eg:
#include <iostream>
using namespace std;
// Declare function printArr here
void printArr(int* arr, int size)
{
for (int i = 0; i < size; i++)
{
cout << arr[i] << ' ';
}
cout << endl;
}
int main()
{
int arr[5] = {1, 3, 5, 7, 9};
const int count = sizeof(arr)/sizeof(arr[0]);
int last_num = arr[count-1];
cout << "Before reversing" << endl;
printArr(arr, count);
// reverse "arr" using reference(&)
cout << "After reversing" << endl;
printArr(arr, count);
return 0;
}
Live Demo
This is a particularly strange question, but i'm attempting to write a function that swaps the values of two integers without using references or '&'. I don't see how this is even possible. Here's what I have so far.
void swap (int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
This, normally would be the way that I would do it, but since the integers don't permanently change, I have no idea as to how I would do this without referencing. Any suggestions?
Thanks!
You should correct the question title. It says “using references”. That’s the opposite of what you mean, apparently.
Assuming that:
truly no references and pointers allowed, exluding any wrapper tricks
a runtime swap is what you want – as opposed to compile time template trickery
no classes, because that would trivial
I can think of one utterly horrible solution. Make your ints globals.
ridiculous_swap.hpp
#ifndef RIDICULOUS_SWAP_HPP
#define RIDICULOUS_SWAP_HPP
extern int first;
extern int second;
void swap_ints();
#endif // RIDICULOUS_SWAP_HPP
ridiculous_swap.cpp
int first = 0;
int second = 0;
void swap_ints()
{
auto tmp = first;
first = second;
second = tmp;
}
main.cpp
#include "ridiculous_swap.hpp"
#include <iostream>
int main()
{
first = 23;
second = 42;
std::cout << "first " << first << " second " << second << "\n";
// prints: first 23 second 42
swap_ints();
std::cout << "first " << first << " second " << second << "\n";
// prints: first 42 second 23
}
It’s not useful for anything, but it does swap two integers without using references or pointers.
There is this old trick to swap two integer-like variables without using a temporary variable:
void swap(int& a, int& b)
{
a ^= b;
b ^= a; // b ^ (a ^b) = a
a ^= b; // (a ^ b) ^ a = b
}
My main idea is to shrink they array from both sides . For example if the input is 1234 , wanna print 1234 and then 4321 (the reversed) .
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
int reversedArray(int* x)
{
cout<< "*x out of while =" << *x <<endl ;
while( *x != 0 )
{
cout << "*x=" << *x << endl;
cout<< "====================== im in reversed =================" << endl ;
return reversedArray( x+1 );
}
cout<< "after return " << *x << endl;
}
int main ()
{
int Array[] = {10,2,3,4,8 ,0} ;
int* p_Array = Array;
reversedArray( Array );
}
After the "while" , why the functions that are in the stack, do not return to the next line ( " the --> cout<< "after return " <<*x <
void printReversed(int * x)
{
if (*x == 0) return;
std::cout << *x;
printReversed(x+1);
std::cout << *x;
}
The line:
return reversedArray( x+1 );
exits the function. So you never repeat the while or execute any of the code after the while if you go into the while. This makes the while effectively an if statement.
The code posted by Crazy Eddie does the job and Barmar explains the ineffectiveness of the while loop. I decided to post a non-recursive way to address the problem mentioned.
#include <iostream>
#include <vector>
using namespace std;
vector<int> reverseArray(vector<int>& arr) {
vector<int> ans;
int n = arr.size();
// insert all elements in the reverse order
for (size_t i = 0; i < n; i++) {
ans.push_back(arr[n-i-1]);
}
return ans;
}
int main ()
{
int array[] = {10, 2, 3, 4, 8, 0};
// convert into vector
vector<int> arr(array, array+6);
vector<int> rev = reverseArray(arr);
// merging the 2 arrays
arr.insert(arr.end(), rev.begin(), rev.end());
// printArray(arr) -- implement to fit your needs;
}
When you pass an int[] to a function it decays to an int* which is simply an address in memory. C++ a better plan would be to use copy_backward with an ostream_iterator:
copy_backward(Array, Array + sizeof(Array) / sizeof(*Array), ostream_iterator<int>(cout, " "))
Note that this method uses the actual size of the array, and does not depend upon a terminal element. Thus, no numbers are offlimits, and it's impossible to segfault by failing to provide the terminating element.
If you have access to C++11 you can simplify that a bit further to:
copy(crbegin(Array), crend(Array), ostream_iterator<int>(cout, " "))
Live Example
#include<iostream>
#include<conio.h>
class Number
{
private:
int x, y;
public:
Number()
{
x = y = 100;
}
void avg()
{
std::cout<<"x = "<<std::cout<<x;
std::cout<<std::endl;
std::cout<<"Y = "<<std::cout<<y;
std::cout<<std::endl;
std::cout<<"Average = "<<std::cout<<(x+y)/2;
}
};
main()
{
Number n;
n.avg();
}
This programme runs but shows wrong answer, may be showing addresses of memory locations instead of showing the assigned values of 100. Please correct me why it is behaving like this?
std::cout << "x = " << std::cout << x;
is wrong. You need
std::cout << "x = " << x;
Otherwise, the std::cout stream object in ...<< std::cout is implicitly converted to a (void*) when invoking operator<< on it, and therefore the pointer (an address) is displayed.
The conversion to void* exists for historic reasons (the safe bool idiom), but in C++11 was removed, due to the introduction of explicit conversion operators, so your code should not compile in C++11.
#include <iostream>
void swap(int &pi, int &pj){
std::cout << "In function swap: " << &pi << " " << &pj << "\n";
int temp = pi;
pi = pj;
pj = temp;
}
int main(){
int i = 10, j = 20;
int *pi = &i, *pj = &j;
swap(pi, pj);
std::cout << *pi << " " << *pj;
return 0;
}
The above program does not give any compilation error. (Though to swap function in not POINTER TO REFERENCE type) and gives the proper output.
But whatever i am trying to print inside "swap" function is not printed to console.
Can anybody explain me why?
Looks like you're probably using std::swap to swap two pointers instead of calling your own swap routine. I suspect you have a using namespace std; somewhere that you are not showing us ? Try changing the name of your swap routine to e.g. my_swap and then see if calling my_swap works (it should fail with a compilation error).
If you can compile your program, you don't show us all of your code.
This code snippet you posted doesn't compile, because you're trying to pass to objects of type int* to your function swapm which expects a reference to an int.
If your code compiles, I suspect you to include a 'using namespace std;' anywhere in your original code.
you're trying to get the address of a pointer that you're passing by reference... I don't think you quite understand what you're doing. the pass by reference feature in C++ allows you to pass a reference, so you don't need a pointer. Your code should look like this.
#include <iostream>
void swap(int &i, int &j){
std::cout << "In function swap: " << i << " " << j << "\n";
int temp = i;
i = j;
j = temp;
}
int main(){
int i = 10, j = 20;
swap(i, j);
std::cout << i << " " << j;
return 0;
}