有的时候,我们需要写一些重复的代码,比如在做一些算法题或者某些项目的时候,我们可能重复书写许多简单的代码像头文件、非常熟悉的算法模板等等,如果你觉得这些是你的负担,那么可以使用vscode添加用户代码片段的功能简化写程序的过程
添加
- 首先打开vscode,看到类似于下面的界面
- 点击上面左下角红圈里面的齿轮图标,选择User Snippets(用户代码片段)
- 可以看到弹出下图所示的菜单
- 这里我要添加的是C++的用户代码片段,所以选择cpp
- 之后会看到下面的界面
- 可以看到里面简单地讲了一下使用方法并给出了一个例子,将注释拿掉
- 前面这个Print to console是代码的名称,可以自己拟定的
- prefix意思是代码的前缀,也就是代码片段触发的关键字,现在设置为log
- body就是代码体
- description就是代码的描述,可以自己解释一下代码什么意思
- 现在创建一个cpp文件,观察这段程序起到了什么样的作用
- 可以看到,已经产生了相应的用户代码片段
- 同理,可以把prefix设置为一个喜欢的英文名字
- 如果需要在一行之前留空可以使用空格或者\t
- 下面是我写的一个例子
{
// Place your snippets for cpp here. Each snippet is defined under a snippet name and has a prefix, body and
// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the
// same ids are connected.
// Example:
"Header file": {
"prefix": "acm",
"body": [
"#include <iostream>",
"#include <cstring>",
"#include <algorithm>",
"#include <queue>",
"#include <stack>",
"using namespace std;",
"typedef long long ll;",
"const int MAXN = 2e5 + 100;",
"int Data[MAXN];",
"int main(){",
"\t$0",
"\treturn 0;",
"}"
],
"description": "Header file"
}
}
- 新建一个cpp文件,输入"acm"显示效果如下
- 上面的代码里面$0意思是光标最后停留的位置,同理也可以有$1、$2等等,光标将首先停留在$1,当按下TABTABTAB键时,光标将向下一个$位置跳转,灵活运用这一点可以飞快书写某些程序,可以自己尝试一下
- 那么如果我们想再写一些其他的代码片段怎么办呢?只需要在这一页下面再新建一个代码片段即可
- 如下所示,加一个快读的模板
{
// Place your snippets for cpp here. Each snippet is defined under a snippet name and has a prefix, body and
// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the
// same ids are connected.
// Example:
"Header file": {
"prefix": "acm",
"body": [
"#include <iostream>",
"#include <cstring>",
"#include <algorithm>",
"#include <queue>",
"#include <stack>",
"using namespace std;",
"typedef long long ll;",
"const int MAXN = 2e5 + 100;",
"int Data[MAXN];",
"int main(){",
"\t$0",
"\treturn 0;",
"}"
],
"description": "Header file"
},
"fast_read":{
"prefix": "read",
"body": [
"inline int read(){",
"\tint x = 0, f = 1;char c = getchar();",
"\twhile(c < '0' || c > '9'){if(c == '-') f = -1;c = getchar();}",
"\twhile(c >= '0' && c <= '9'){x = (x << 1) + (x << 3) + (c ^ 48);c=getchar();}",
"\treturn x*f;",
"}"
],
"description": "fast_read"
}
}
- 这样就写好了两个模板,同理可以写更多的模板
删除
- 如果不想要写好的代码片段,如何去删除呢,只需要找到相应的路径,再使用文件资源管理器删除即可,下面红圈里的就是文件路径
总结
- 用户代码片段虽然用起来可能比较舒服,但是只适用于一些非常死板的没有必要费脑筋的大段代码,不要因为懒惰就把一些生疏的模板代码放在上面不加思索地使用,这样很不利于成长