With C ++ 0x / C ++ 11 you can use this:
#include <string> #include <iostream> #include <tuple> using namespace std; tuple<int, unsigned, string, int> getValues() { return tuple<int, unsigned, string, int>(1, 2, "3", 4); } int main() { int a; unsigned b; string c; int d; tie(a, b, c, d) = getValues(); cout << a << ", " << b << ", " << c << ", " << d << endl; return 0; }
Compile it with
g++ tuple_test.cpp -std=c++0x -o tuple_test
And if you run the program, it will output this:
1, 2, 3, 4
But it is better to use such links (I would say):
void getValues(int& a, unsigned& b, string& c, int& d) { a = 1; b = 2; c = "3"; d = 4; } int main() { ... getValues(a, b, c, d) ... }
Uch is what I get for not carefully reading the question ...
Can a function return only one value if it is not a pointer to an array?
Yes, you can return only one value, but this single value can include multi-valued values ββ(struct, class, array).
You can return multiple data elements using a structure, but using a pointer (I don't understand this) uses memory more efficiently. Is it correct?
True But when you use pointers, it depends on how you use it. When you dynamically allocate it, each function call will not be very efficient, and you will need to free memory manually after use. When you use a global array / structure, it will be efficient. But it can cause problems when you call the function to multiply time.