目录
在这里我们先实现 (部分实现) 一些python中易用的函数,看下效果
实现的函数模块位置如下
tasks.json 配置修改如下
prints
功能:打印字符串
lib/pyfunc.cpp里函数实现如下
void prints(string str)
{ cout << str << endl; }
lib/pyfunc.cpp里函数声明如下
void prints(string str);
main.cpp如下
运行结果如下
hello world
注意
下面展示的函数例子,函数的实现在lib/pyfunc.cpp, lib/pyfunc.h里只有函数声明;
运行代码是main.cpp,在main.cpp里包含lib/pyfunc.h头文件,因为头文件和库文件同名,后缀名不一样而已,所以main.cpp只需要包含头文件即可。
下面的例子代码有3块
- 第一块:函数实现放在lib/pyfunc.cpp
- 第二块:main.cpp内容或main函数内容
- 第三块:main.cpp编译执行结果
下面的例子代码也有1块的,表示函数实现部分,放在lib/pyfunc.cpp里
printi
功能:打印整数
void printi(int i)
{ cout << i << endl; }
#include <iostream>
#include <vector>
#include "lib/pyfunc.h"
using namespace std;
int main()
{
int a = 1024;
printi(a);
}
1024
printF
功能:打印实数
为了区分C++中的printf
void printF(float f)
{ cout << f << endl; }
int main()
{
float f = 0.9;
printF(f);
}
0.9
printpii
功能:打印<int,int>类型的pair
void printpii(pair<int,int> p)
{
int first,second;
tie(first,second) = p;
cout << "(" << first << "," << second << ")\n";
}
int main()
{
pair<int,int> p={1024,520};
printpii(p);
}
(1024,520)
printpif
功能:打印<int,float>类型的pair
void printpif(pair<int,float> p){
int first; float second;
tie(first,second) = p;
cout << "(" << first << "," << second << ")\n";
}
int main()
{
pair<int,float> p={2,0.9};
printpif(p);
}
(2,0.9)
printpis
功能:打印<int,string>类型的pair
void printpis(pair<int,string> p){
int first; string second;
tie(first,second) = p;
cout << "(" << first << "," << second << ")\n";
}
printpfi
功能:打印<float,int>类型的pair
void printpfi(pair<float,int> p){
float first; int second;
tie(first,second) = p;
cout << "(" << first << "," << second << ")\n";
}
printpff
功能:打印<float,float>类型的pair
void printpff(pair<float,float> p){
float first,second;
tie(first,second) = p;
cout << "(" << first << "," << second << ")\n";
}
printpfs
功能:打印<float,string>类型的pair
void printpfs(pair<float,string> p){
float first; string second;
tie(first,second) = p;
cout << "(" << first << "," << second << ")\n";
}
printpsi
功能:打印<string,int>类型的pair
void printpsi(pair<string,int> p){
string first; int second;
tie(first,second) = p;
cout << "(" << first << "," << second << ")\n";
}
printpsf
功能:打印<string,float>类型的pair
void printpsf(pair<string,float> p){
string first; float second;
tie(first,second) = p;
cout << "(" << first << "," << second << ")\n";
}
printpss
功能:打印<string,string>类型的pair
void printpss(pair<string,string> p){
string first, second;
tie(first,second) = p;
cout << "(" << first << "," << second << ")\n";
}
printvi
功能:打印<int>类型的vector
void printvi(vector<int> v){
cout << "[";
for (int i=0; i<v.size(); i++)
{
if (i<v.size()-1){
cout << v[i] << ", ";
}
else {
cout << v[i] << "]\n";
}
}
}
printvf
功能:打印<float>类型的vector
void printvf(vector<float> v){
cout << "[";
for (int i=0; i<v.size(); i++)
{
if (i<v.size()-1){
cout << v[i] << ", ";
}
else {
cout << v[i] << "]\n";
}
}
}
printvs
功能:打印<string>类型的vector
void printvs(vector<string> v){
cout << "[";
for (int i=0; i<v.size(); i++)
{
if (i<v.size()-1){
cout << v[i] << ", ";
}
else {
cout << v[i] << "]\n";
}
}
}