May
May

Reputation: 15

Use a pair as a parameter from another function

I have a function that returns a std::pair<int, double>.

I want to create another function to use the pair from the previous function and view the data in the pair, i.e. both first and second. Is it possible to pass the return of the previous function as a parameter for my new function so the second function can view the data? I am unsure about the syntax in C++.

Upvotes: 1

Views: 11773

Answers (2)

skypjack
skypjack

Reputation: 50540

I guess you mean something like the example above:

#include <utility>

std::pair<int, double> create() {
    return std::make_pair(4, 2.);
}

void accept(std::pair<int, double> p) { }

int main() {
    accept(create());
}

The response is yes, you can do it.

If you don't want to pass to accept a copy of the pair, instead you want to submit the exact instance of it you are working with in the main function, you can slightly modify the functions prototype as it follows:

#include <utility>

std::pair<int, double> create() {
    return std::make_pair(4, 2.);
}

void accept(std::pair<int, double>& p) { }

int main() {
    auto p = create();
    accept(p);
}

And so on...

Upvotes: 1

P0W
P0W

Reputation: 47784

void func2( const std::pair <int, double>& data )
{

}

std::pair <int, double> func1 ( /* ... * / )
{
   //return pair
}

Then call

 func2 ( fun1( /*... */ ) );

Upvotes: 2

Related Questions