Returning vectors of vector

Hi all,

1
2
3
4
5
6
7
8
9
10
11
12
13
 std::vector<float> TEST()
    {
    std::vector<float> ws;
    std::vector<float> space;
    int count =0; 

    // Do stuffs

    
    }  
  return ws,space;
  }


How to return the ws and space in the above Function TEST. And I am calling the
function as:

v1,v2 = TEST();

If I check the result I am only getting the v2 vector. Both are overwriting.
How to rectify the above problem?

Thank you.
To return a vector of vectors, your return type should be:

std::vector<std::vector<float>>

If you find that syntax hard to read, you could make it clearer using typedefs, e.g.

1
2
3
4
5
6
7
8
9
typedef std::vector<float> FloatVector;

std::vector<FloatVector> TEST()
{
  std::vector<FloatVector> retVector;
  // ...

  return retVector;
}


If I check the result I am only getting the v2 vector. Both are overwriting.

Nothing is overwriting anything. The problem is that you are using the comma operator without understanding what it actually does.
Last edited on
You can return the two vectors as a pair then extract when the function called. Consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <utility>
#include <vector>

auto TEST()
{
	std::vector<float> ws;
	std::vector<float> space;
	int count = 0;

	// Do stuffs


	return std::pair (ws, space);
}


int main()
{
	auto [v1, v3] = TEST();

	// use v1 and v2 as vector<float>
}


If you need to return more than 2 items then you could use std::tuple rather than std::pair.


PS You'll need at least C++17 for this to compile.
Last edited on
Topic archived. No new replies allowed.