2013-03-12 3 views
9

두 개의 이중 변수를 반환하고 싶습니다. 내가 만든 함수를 호출 할 때. 일부 자습서 (C++의 기본 사항을 다루는)에 따르면이 작업을 수행 할 수 없습니다.C++ 함수에서 두 변수 반환

이렇게 할 방법이 있습니까?

+1

가 그리고 C++ 11은'tie'를 사용할 수있는 것은 http://stackoverflow.com/q/321068/10077을 할당 –

답변

16

당신은 당신은 예를 들면, std::pair을 사용할 수 있습니다

void setTwoDoubles(double& d1, double& d2) 
{ 
    d1 = 1.0; 
    d2 = 2.0; 
} 

double d1, d2; 
setTwoDoubles(d1, d2); 
std::cout << "d1=" << d1 << ", d2=" << d2 << std::endl 
6

함수 내에서 그 값을 설정하는 기능으로이 두 배에 대한 참조를 전달할 수 있습니다.

+3

다음을 참조하십시오 std::tuple 페이지에서 가져온

예 나는에 링크 직접 두 변수로. –

0

하나의 함수에서 두 개의 값을 반환 할 수는 없지만 배열이나 두 개의 double을 포함하는 다른 구조체에 대한 포인터를 반환 할 수는 있습니다.

19

당신은 변수를 보유하고 간단한 구조체를 작성하고 반환 또는 std::pair 또는 std::tuple 사용할 수 있습니다

#include <utility> 

std::pair<double, double> foo() 
{ 
    return std::make_pair(42., 3.14); 
} 

#include <iostream> 
#include <tuple> // C++11, for std::tie 
int main() 
{ 
    std::pair<double, double> p = foo(); 
    std::cout << p.first << ", " << p.second << std::endl; 

    // C++11: use std::tie to unpack into pre-existing variables 
    double x, y; 
    std::tie(x,y) = foo(); 
    std::cout << x << ", " << y << std::endl; 

    // C++17: structured bindings 
    auto [xx, yy] = foo(); // xx, yy are double 
} 
+1

['std :: tie'] (http://en.cppreference.com/w/cpp/utility/tuple/tie)도 언급 할 수 있습니다. 기존 변수. –

+0

@ BenjaminLindley 좋습니다.예를 추가했습니다. – juanchopanza

3

기술적를, 당신이 방법으로 두 개의 변수를 반환 할 수없는 어떤 당신은 반환 평소 없다 변수. 그러나 참조를 사용할 수는 있습니다. 그런 식으로, 당신은 함수에 여러 변수를 전달할 수 있고, 함수가 아니라 아무것도 돌아보다,에 할당됩니다

void function(double & param1, double & param2) { 
    param1 = 6.28; 
    param2 = 3.14; 
} 

을 그리고 당신은 이런 식으로 부를 것이다 :

double var1, var2; 
function(var1, var2); 
2

을 당신은 할 수 없습니다 직접 처리하십시오 (반환 값이 단일이기 때문에).
그러나 구조체에 몇 가지 값을 넣고 그 값을 반환 할 수 있습니다 (<>와 같이).

일반적인 패턴은 참조로 출력 변수를 반환하는 것입니다 :

ReturnVal Myfunction(/*in*/ BlahType _someParameters, /*out*/ ReturnType& _firstReturn, /*out*/ OtherReturnType& _secondReturn) 
{ 
    _firstReturn = //someStuff 
    _secondReturn = //someOtherStuff 


return SUCCESS; 
} 
3

없음 당신은 출력이 (100)가 될 것

#include <iostream> 
using namespace std; 

// function declaration 
void swap(int &x, int &y); 

int main() 
{ 
    // local variable declaration: 
    int a = 100; 
    int b = 200; 

    cout << "Before swap, value of a :" << a << endl; 
    cout << "Before swap, value of b :" << b << endl; 

    /* calling a function to swap the values using variable reference.*/ 
    swap(a, b); 

    cout << "After swap, value of a :" << a << endl; 
    cout << "After swap, value of b :" << b << endl; 

    return 0; 
} 


// function definition to swap the values. 
void swap(int &x, int &y) 
{ 
    int temp; 
    temp = x; /* save the value at address x */ 
    x = y; /* put y into x */ 
    y = temp; /* put x into y */ 

    return; 
} 

로 참조 방법으로 사용해야하는 두 개의 변수를 반환 할 수 없습니다 // 스왑 함수를 호출하기 전에 x 200 // 스왑 함수를 호출하기 전에 y 200 // 스왑 함수를 호출 한 후 x 100 // y 스왑 함수를 호출 한 후

이 반환 등 두 값

this link help you

11

당신이 C++ (11)를 사용하는 경우, 나는 이상적인 방법은 std::tuplestd::tie을 사용하는 것입니다라고 말하고 싶지만.

에게
#include <tuple> 
#include <iostream> 
#include <string> 
#include <stdexcept> 

std::tuple<double, char, std::string> get_student(int id) 
{ 
    if (id == 0) return std::make_tuple(3.8, 'A', "Lisa Simpson"); 
    if (id == 1) return std::make_tuple(2.9, 'C', "Milhouse Van Houten"); 
    if (id == 2) return std::make_tuple(1.7, 'D', "Ralph Wiggum"); 
    throw std::invalid_argument("id"); 
} 

int main() 
{ 
    auto student0 = get_student(0); 
    std::cout << "ID: 0, " 
       << "GPA: " << std::get<0>(student0) << ", " 
       << "grade: " << std::get<1>(student0) << ", " 
       << "name: " << std::get<2>(student0) << '\n'; 

    double gpa1; 
    char grade1; 
    std::string name1; 
    std::tie(gpa1, grade1, name1) = get_student(1); 
    std::cout << "ID: 1, " 
       << "GPA: " << gpa1 << ", " 
       << "grade: " << grade1 << ", " 
       << "name: " << name1 << '\n'; 
}