制作动态数组并在c ++中返回两个值

时间:2017-01-23 08:40:55

标签: c++ arrays

我编写了以下用于制作动态数组的代码,并从函数中获取了两个值 但是有一些问题,例如:

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

还有:

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)

这里有什么问题?

#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;
}

2 个答案:

答案 0 :(得分: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;
}

用户657267指出你试图将char转换为int *。我通过分配1个元素的数组来改变它 对于unpair部分,您必须实例化该类才能使用=运算符。

答案 1 :(得分:0)

您的t_unpair类型已存在,名为std::tie

请注意,dosomething值得知道a中有多少元素,因此它只能访问存在的int

#include <iostream>
#include <tuple>

// Our function that returns a pair, defined elsewhere
pair<int*,float> dosomething( char c );

// And how we test the pair. 
////////////
int main()
{
    int *a; // don't allocate here, dosomething will overwrite that assignment
    float b;
    std::tie( a, b ) = dosomething( 'A' );
    std::cout << a << ", " << b << std::endl;
    return 0;
}

通过原始指针传输数组的所有权是邀请未定义的行为。 std::vector更合适。