我试图在名为x的向量上对cpp进行合并排序,该向量包含x坐标。当mergesort对x坐标进行排序时,它应该在一个名为y的向量中移动相应的元素,包含y坐标。唯一的问题是我不知道如何(或者如果我可以)从合并函数返回两个结果向量。 或者,如果它更容易实现,我可以使用较慢的排序方法。
答案 0 :(得分:3)
不,你不能从这个例子中的方法返回2个结果。
vector<int>, vector<int> merge_sort();
你可以做的是通过引用函数传递2个向量,并且得到的mergesorted向量影响2个向量...例如
void merge_sort(vector<int>& x, vector<int>& y);
最终,您可以执行@ JoshD提到的内容并创建一个名为struct
的点并合并排序点结构的向量。
答案 1 :(得分:1)
尝试这样的事情:
struct Point {
int x;
int y;
operator <(const Point &rhs) {return x < rhs.x;}
};
vector<Point> my_points.
mergesort(my_points);
或者,如果您想通过y坐标对具有相等x值的点进行排序:
另外,我想我会补充一下,如果你真的需要,你可以一直返回std::pair
。更好的选择通常是返回函数参数。
operator <(const Point &rhs) {return (x < rhs.x || x == rhs.x && y < rhs.y);}
答案 2 :(得分:0)
是的,您可以返回一个元组,然后使用结构化绑定(自C ++ 17开始)。
这是一个完整的例子:
#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;
}
答案 3 :(得分:0)
你可以有一个向量的向量 => 向量<向量> 点 = {{a, b}, {c, d}}; 现在您可以返回积分了。
答案 4 :(得分:-1)
返回向量很可能不是您想要的,因为它们是为此目的而复制的(这很慢)。例如,请查看this implementation。