MST

星途 面试题库

面试题:C++中复杂类型的transform链式操作

定义一个结构体 `Point`,包含 `int x` 和 `int y` 两个成员变量。有一个 `std::vector<Point>` 名为 `points`。请使用 `std::transform` 的链式操作,将 `points` 中每个 `Point` 的 `x` 和 `y` 坐标都增加10,然后将所有 `x` 坐标大于50的 `Point` 筛选出来,存储到另一个 `std::vector<Point>` 中,并输出筛选后的 `vector` 的内容。请编写完整的C++代码实现,包括结构体定义和所需的头文件等。
33.7万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>
#include <vector>
#include <algorithm>

// 定义结构体
struct Point {
    int x;
    int y;
};

int main() {
    std::vector<Point> points = { {10, 20}, {40, 30}, {60, 50} };
    std::vector<Point> result;

    // 使用std::transform的链式操作
    std::transform(points.begin(), points.end(), std::back_inserter(result), [](const Point& p) {
        Point newP = p;
        newP.x += 10;
        newP.y += 10;
        return newP;
    });

    result.erase(std::remove_if(result.begin(), result.end(), [](const Point& p) {
        return p.x <= 50;
    }), result.end());

    // 输出筛选后的vector内容
    for (const auto& p : result) {
        std::cout << "x: " << p.x << ", y: " << p.y << std::endl;
    }

    return 0;
}