开发者

is it possible to return two vectors from a function?

Im trying to do a merge sort in cpp on a vector called x, which contains x coordinates. As the merges开发者_Python百科ort sorts the x coordinates, its supposed to move the corresponding elements in a vector called y, containing the y coordinates. the only problem is that i dont know how to (or if i can) return both resulting vectors from the merge function. alternatively if its easier to implement i could use a slower sort method.


No, you cannot return 2 results from a method like in this example.

vector<int>, vector<int> merge_sort();

What you can do is pass 2 vectors by reference to a function and the resultant mergesorted vector affects the 2 vectors...e.g

void merge_sort(vector<int>& x, vector<int>& y);

Ultimately, you can do what @JoshD mentioned and create a struct called point and merge sort the vector of the point struct instead.


Try something like this:

struct Point {
  int x;
  int y;
  operator <(const Point &rhs) {return x < rhs.x;}
};

vector<Point> my_points.

mergesort(my_points);

Or if you want to sort Points with equal x value by the y cordinate:

Also, I thought I'd add, if you really ever need to, you can alway return a std::pair. A better choice is usually to return through the function parameters.

  operator <(const Point &rhs) {return (x < rhs.x || x == rhs.x && y < rhs.y);}


Yes, you can return a tuple, then use structured binding (since C++17).

Here's a full example:

#include <cstdlib>
#include <iostream>
#include <numeric>
#include <tuple>
#include <vector>

using namespace std::string_literals;

auto twoVectors() -> std::tuple<std::vector<int>, std::vector<int>>
{
    const std::vector<int> a = { 1, 2, 3 };
    const std::vector<int> b = { 4, 5, 6 };
    return { a, b };
}

auto main() -> int
{
    auto [a, b] = twoVectors();
    auto const sum = std::accumulate(a.begin(), a.end(), std::accumulate(b.begin(), b.end(), 0));
    std::cout << "sum: "s << sum << std::endl;
    return EXIT_SUCCESS;
}


You can have a vector of vectors => vector<vector > points = {{a, b}, {c, d}}; now you can return points.


Returning vectors is most probably not what you want, as they are copied for this purpose (which is slow). Have a look at this implementation, for example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜