#include <bits/stdc++.h>
using namespace std;
int* insertionSort(int* a);
int main()
{
int a[5];
for(int i=0;i<5;i++)
{
cin>>a[i];
}
int b[5];
*b = insertionSort(a);
for(int i=0;i<5;i++)
{
cout<<b[i]<<" ";
}
}
int* insertionSort(int* a)
{
for(int i=1;i<5;i++)
{
int key=a[i];
int j=i-1;
while(j>0 && a[j]>key)
{
a[j]=a[j+1];
j-=1;
}
a[j+1]=key;
}
return a;
}
So this is my code for insertion sort. But when I run this it gives me the error
insertionSort.cpp: In function ‘int main()’:
insertionSort.cpp:15:21: error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
*b = insertionSort(a);
I would like to know how does passing and returning arrays in functions work in C++. What is the error in my code?
P.S : It may happen that my insertion code may be wrong. I have not really tested it so pardon me I could not check it because of this error. It would be really helpful if someone can explain it in detail.
insertionSort is returning a int pointer, and you're trying to assign it to an int by dereferencing the pointer (*b). The correct syntax would be
b = insertionSort(a);
Also, b should be declared as int* b
P.S., this compiles, but still doesn't work as intended, but that's a whole different question from the one you posed.
#include <array>
#include <algorithm> // sort
#include <iostream>
constexpr size_t size {5};
std::array<int, size>* insertionSort(std::array<int, size>& a)
{
std::sort(a.begin(), a.end());
return &a;
}
int main()
{
std::array<int, size> a {1, 4, 3, 2, 5};
std::array<int, size>* b = insertionSort(a);
for(size_t i = 0; i < size; ++i)
std::cout << (*b)[i] << std::endl;
}
You should use the standard library functions when possible (here the sort one)
Thanks to C++11 we know have array (instead of playing with raw pointers)
Related
I am working on my own library and I want to create function max(). I know that function like this exists in C++ and it isn't in namespace std, so erasing using namespace std; won't help. I am creating this function in my namespace like this:
namespace ml
{
template<typename T>T max(T cntr, int size)//I'm getting errors here
{
sort(cntr,0,size-1);//my function which just sorts elements, it's working fine
return cntr[size-1];
}
}
Here is my main function:
#include <iostream>
#include <ctime>
#include "mylib.hpp"
int main()
{
srand(time(NULL));
int* arr, n;
std::cin>>n;
arr = new int [n];
for(int i = 0; i < n; i++)
{
arr[i] = rand()%100;
}
int maximum = ml::max(arr,n);//I'm getting errors here
std::cout<<maximum<<'\n';
return 0;
}
Sorry for grammatical mistakes if i've done so.
If the purpose of the function is to search a C-style array, the signature should be template <typename T> T max(T* cntr, int size). (note the T* as the type of cntr) That way, when it's called with an int*, T is deduced as int, and that's the correct return type.
This small example is giving the error message
Error C2440 '=': cannot convert from '_Ux (*const )' to 'int *' Templ 1266
Error C3692 non-scalar type 'int []' cannot be used in a pseudo-destructor expression
What is _Ux(*const)?
This is the program:
#include <memory>
int main()
{
shared_ptr<int[]> as = make_shared<int[]>(10);
for (int i = 0; i < 10; i++) {
as[i] = i + 100;
}
}
The code as shown does not compile, because shared_ptr and make_shared() are in the std namespace, but there is no using namespace std; statement, or at least using std::shared_ptr; and using std::make_shared; statements.
However, fixing that, make sure you are compiling this code for C++20, as std::make_shared() does not support the creation of arrays in earlier versions, which can lead to the error you are seeing.
In C++17, you will have to construct the array manually instead, but std::shared_ptr will free the array correctly, eg:
std::shared_ptr<int[]> as( new int[10] );
Live Demo
But, std::shared_ptr does not support arrays at all in C++11 and C++14, so you will have to use a custom deleter to free the array properly, and use std::shared_ptr::get() instead of std::shared_ptr::operator[] to access the array elements, eg:
#include <memory>
int main()
{
std::shared_ptr<int> as( new int[10], [](int *p) { delete[] p; } );
for (int i = 0; i < 10; i++) {
as.get()[i] = i + 100;
}
}
For dynamic arrays, you should consider using std::vector instead, eg:
#include <vector>
int main()
{
std::vector<int> as(10);
for (int i = 0; i < 10; i++) {
as[i] = i + 100;
}
}
Write a program to solve Coin-row problem using dynamic programming (in c++)
Given the coin row: 5,1,2,10,6,2
I wrote the code, but I get an error about the size. Why?
this is code
#include<iostream>
using namespace std;
int max(int a,int b){
if(a>b)
return a;
else
return b;
}
int main(){
int coinrow[]={5,1,2,10,6,2};
int size=sizeof(coinrow)/sizeof(coinrow[0]);
//cout<<size;
int i;
int coins[size+1];
for(i=0;i<size;i++){
coins[i+1]=coinrow[i];
}
int F[size+1];
F[0]=0;
F[1]=coins[1];
for(i=2;i<=size;i++){
F[i]=max(coins[i]+F[i-2],F[i-1]);
}
cout<<F[size];
}
The size of an array has to be a compile time constant and known at compile time. int coins[size+1]; is a variable-length array (because size is not a compile time constant) and not valid C++. Some compilers support it with compiler extensions but its usage is limited. The memory is allocated on the stack and the stack size is limited. Larger arrays should be allocated on the heap. Use std::vector (heap) or const/constexpr (stack) instead of VLAs. const doesn't guarantee a compile time constant.
#include<iostream>
using namespace std;
int max(int a,int b){
if(a>b)
return a;
else
return b;
}
int main(){
int coinrow[]={5,1,2,10,6,2};
constexpr int size=sizeof(coinrow)/sizeof(coinrow[0]);
//cout<<size;
int i;
int coins[size+1];
for(i=0;i<size;i++){
coins[i+1]=coinrow[i];
}
int F[size+1];
F[0]=0;
F[1]=coins[1];
for(i=2;i<=size;i++){
F[i]=max(coins[i]+F[i-2],F[i-1]);
}
cout<<F[size];
}
I prefer
#include <algorithm>
#include <array>
#include <iostream>
int main(){
std::array coinrow = {5,1,2,10,6,2};
constexpr auto size = coinrow.size();
//cout<<size;
std::array<int, size+1> coins;
for(std::size_t i=0;i<size;i++){
coins[i+1]=coinrow[i];
}
std::array<int, size+1> F;
F[0]=0;
F[1]=coins[1];
for(std::size_t i=2;i<=size;i++){
F[i]=std::max(coins[i]+F[i-2],F[i-1]);
}
std::cout<<F[size];
}
if the size is known at compile time and the stack can be used and
#include <algorithm>
#include <iostream>
#include <vector>
int main(){
std::vector coinrow = {5,1,2,10,6,2};
auto size = coinrow.size();
//cout<<size;
std::vector<int> coins(size+1);
for(std::size_t i=0;i<size;i++){
coins[i+1]=coinrow[i];
}
std::vector<int> F(size+1);
F[0]=0;
F[1]=coins[1];
for(std::size_t i=2;i<=size;i++){
F[i]=std::max(coins[i]+F[i-2],F[i-1]);
}
std::cout<<F[size];
}
if the size not known at compile time or the heap has to be used.
how do i iterate the pair array arguments passed as a pointer ?
i had tried to use as reference pair &arr . but it doesnt worked either . can i pass pair<lli,lli> a[n]; as reference ??
#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")
#define LOCAL
#include <bits/stdc++.h>
using namespace std;
#define ff first
#define ss second
typedef long long int lli;
typedef unsigned long long int ulli;
void yeah( pair<lli,lli> *arr ){
// cout << arr[0].ff; 100
//this doesnt work :(
for(auto e : arr){
cout << e.ff << " " << e.ss << endl;
}
}
int main() {
int n = 10;
pair<lli,lli> a[n];
a[0].ff = 100;
a[1].ss = 150;
yeah(a);
}
this is the error im getting
prog.cpp: In function 'void yeah(std::pair)':
prog.cpp:13:18: error: no matching function for call to 'begin(std::pair&)'
for(auto e : arr){
^
^
A possible solution with fixed-size arrays:
template<std::size_t size>
void foo(std::pair<int, int> (&arr)[size]) {
for (auto e : arr) {
...
}
}
constexpr std::size_t n = 10; // should be known at compile time
std::pair<int, int> a[n];
foo(a);
I would recommend ditching the VLA (which is not part of C++ anyway) and use std::vector instead. Include <vector> and change the declaration to this:
std::vector<std::pair<lli, lli>> a(n);
And the function's signature to:
void yeah(std::vector<std::pair<lli, lli>> &arr)
Admittedly, I'm just finding my footsteps in C++ but I don't understand the error here.
The following error gets displayed:
Error 1 error C3312: no callable 'begin' function found for type 'int []'
Error 2 error C3312: no callable 'end' function found for type 'int []'
Error 3 error C2065: 'i' : undeclared identifier
4 IntelliSense: this range-based 'for' statement requires a suitable "begin" function and none was found
Code:
#include <iostream>
using namespace std;
void printArray(int[]);
int main() {
int a[] = { 1, 2, 3, 4, 5 };
printArray(a);
system("pause");
return 0;
}
void printArray(int a[]) {
for (int i : a) {
cout << i << " ";
}
}
Can't figure out what the problem is.
Inside printArray, a is not an array! I know it looks like one, but it's not. int a[] there means int* a, due to a nasty legacy from the 1850s.
Here is the fix to your problem, passing in the array by reference and therefore keeping its full type (including numerical dimension):
#include <iostream>
template <size_t N>
void printArray(int (&a)[N]) {
for (int i : a) {
std::cout << i << " ";
}
}
int main() {
int a[] = { 1, 2, 3, 4, 5 };
printArray(a);
}
(I've also removed some redundant code and that horrid system("pause"): properly configure your execution environment rather than having your program take responsibility for blocking its caller when it's finished!)
(live demo)
void printArray(int a[])
Despite that function seeming to accept an array, what it actually gets is a pointer to the first element of said array. This is unfortunately a fact of life in C++, due to it's origins based on the C language.
And, as a pointer itself has no size information about the underlying array, no iterators are available for it, so begin and end will not work.
There are ways to do this with templates but, in this case, I'd probably just bite the bullet and use a vector:
#include <iostream>
#include <vector>
void printArray (const std::vector<int> &a) {
for (int i : a)
std::cout << i << ' ';
std::cout << '\n';
}
int main () {
const std::vector<int> a = { 1, 2, 3, 4, 5 };
printArray (a);
return 0;
}