How to return multiple values from function in C++

3 Answers

0 votes
#include <iostream>

auto f() {
  struct values {        
    int a, b;
    std::string s;
  };
  return values {12, 837, "c++"}; 
}

int main() {
  auto [value1, value2, value3] = f(); 
  
  std::cout << value1 << ", " << value2 << ", " << value3;

  return 0;
}



/*
run:

12, 837, c++

*/

 



answered May 14, 2021 by avibootz
0 votes
#include <iostream>
#include <tuple>

std::tuple<int, float, std::string> f() {
  return {12, 3.14, "c++"};
}

int main() {
  auto [value1, value2, value3] = f(); 
  
  std::cout << value1 << ", " << value2 << ", " << value3;

  return 0;
}




/*
run:

12, 3.14, c++

*/

 



answered May 14, 2021 by avibootz
0 votes
#include <iostream>

std::pair<int, int> f() {
    std::pair<int, int> pr;

    pr.first = 23;
    pr.second = 848;
    
    return pr;
}


int main() {
    auto pr = f();
    
    std::cout << pr.first << " " << pr.second;

    return 0;
}




/*
run:

23 848

*/

 



answered May 14, 2021 by avibootz

Related questions

1 answer 155 views
1 answer 151 views
1 answer 101 views
4 answers 136 views
4 answers 137 views
1 answer 80 views
1 answer 101 views
...