面试题答案
一键面试#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
// 计算点到原点的距离
double distance(const std::vector<int>& point) {
return std::sqrt(point[0] * point[0] + point[1] * point[1]);
}
// 比较函数
bool comparePoints(const std::vector<int>& a, const std::vector<int>& b) {
double distA = distance(a);
double distB = distance(b);
if (distA != distB) {
return distA < distB;
} else if (a[0] != b[0]) {
return a[0] < b[0];
} else {
return a[1] < b[1];
}
}
// 排序函数
void sortPoints(std::vector<std::vector<int>>& matrix) {
std::sort(matrix.begin(), matrix.end(), comparePoints);
}
你可以通过以下方式调用这个函数:
int main() {
std::vector<std::vector<int>> matrix = {
{1, 3},
{2, 2},
{4, 1}
};
sortPoints(matrix);
for (const auto& point : matrix) {
std::cout << "{" << point[0] << ", " << point[1] << "}" << std::endl;
}
return 0;
}