把leetcode上的代码段搬到本地编译

在leetcode上刷题时,有时候想把代码片段放到本地来学习编译,下面来介绍c++语言操作方法。后续有时间还会更新演示python、golang和C语言的版本。本地操作环境是Centos7,已安装了gcc核g++. 以《剑指 Offer》 II 088. 爬楼梯的最少成本问题为例(https://leetcode-cn.com/problems/GzCJIP/).找到"题解"下的官方讲解中的C++答案标签页,是如下内容:

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        int n = cost.size();
        int prev = 0, curr = 0;
        for (int i = 2; i <= n; i++) {
            int next = min(curr + cost[i - 1], prev + cost[i - 2]);
            prev = curr;
            curr = next;
        }
        return curr;
    }
};

然后在本地建一个test.cpp文件,编辑文件内容如下:

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        int n = cost.size();
        int prev = 0, curr = 0;
        for (int i = 2; i <= n; i++) {
            int next = min(curr + cost[i - 1], prev + cost[i - 2]);
            prev = curr;
            curr = next;
        }
        return curr;
    }
};
 
int main()
{
    Solution s;
    
    vector<int> vecTest;
    vecTest.clear();
    vecTest.push_back(10);
    vecTest.push_back(15);
    vecTest.push_back(20);
    int ret =  s.minCostClimbingStairs(vecTest); 
    cout<<"display minimum cost:"<<endl;
    cout << ret <<endl;
    return 0;
}

编译方法如下

  1. g++ test.cpp -o test
  2. gcc test.cpp -lstdc++ -o test
    以上两种方法都可以,如果不加-o得出的二进制文件名为a.out. 然后运行原则编译出来的二进制文件就可以了。
原文地址:https://www.cnblogs.com/janeysj/p/15703111.html