Make a dynamic array and return two values ​​in c ++

advertisements

I wrote the following code for making dynamic array and also get two value from function but there are problems such as :

Error   1   error C2664: 'std::make_pair' : cannot convert parameter 1 from 'int' to 'int *&&'

and also :

Error   2   error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::pair<_Ty1,_Ty2>' (or there is no acceptable conversion)

What is wrong here ?

#include <iostream>
#include <map>
#include <string>
using namespace std;

// Our template functor
template <typename T1, typename T2>
struct t_unpair
{
    T1& a1;
    T2& a2;
    explicit t_unpair( T1& a1, T2& a2 ): a1(a1), a2(a2) { }
    t_unpair<T1,T2>& operator = (const pair<T1,T2>& p)
    {
        a1 = p.first;
        a2 = p.second;
        return *this;
    }
};

// Our functor helper (creates it)
template <typename T1, typename T2>
t_unpair<T1*,T2> unpair( T1& a1, T2& a2 )
{
    return t_unpair<T1,T2>( a1, a2 );
}

// Our function that returns a pair
pair<int*,float> dosomething( char c )
{
    return make_pair<int*,float>( c*10, c*2.9 );
}

// And how we test the pair.
////////////
int main()
{
    int size;

    // size would be variable but here we consider it one!
    size=1;

    int *a = new int[size];

    float b;
    unpair( a, b ) = dosomething( 'A' );
    cout << a << ", " << b << endl;
    delete [] a;
    return 0;
}


#include <iostream>
#include <map>
#include <string>
using namespace std;

// Our template functor
template <typename T1, typename T2>
struct t_unpair
{
    T1& a1;
    T2& a2;
    explicit t_unpair(T1& a1, T2& a2) : a1(a1), a2(a2) { }
    t_unpair<T1, T2>& operator = (const pair<T1, T2>& p)
    {
        a1 = p.first;
        a2 = p.second;
        return *this;
    }
};

// Our functor helper (creates it)
template <typename T1, typename T2>
t_unpair<T1*, T2> unpair(T1& a1, T2& a2)
{
return t_unpair<T1, T2>(a1, a2);
}

// Our function that returns a pair
pair<int*, float> dosomething(char c)
{
    int* myInt = new int(c);
    return make_pair(myInt, c*2.9);
}

// And how we test the pair.
////////////
int main()
{
    int size;

    // size would be variable but here we consider it one!
    size = 1;

    int *a = new int[size];

    float b;
    t_unpair<int*, float> myUnpair(a, b);
    myUnpair= dosomething('A');
    cout << *a << ", " << b << endl;
    delete[] a;
    return 0;
}

As user657267 pointed out you tried to convert a char to an int*. I changed that by allocating an array of 1 element.
And for the unpair part you have to instantiate the class to be able to use the =operator.