0 简单 c++转 js 代码
- 函数头部返回值=>
function
, 参数列表去类型
-
int|double|string
>= var
-
.size()
=> .length
-
/ 2
=> >>1
function cpp2js(str){
var from = str.split('\n'), to = [];
for(var s of from){
var out = s;
var func = /\w+\s+(\w+)\s*\(((<.*>|[^<>])*)\)/
if(func.test(s)){
out = "function ";
out += RegExp.$1 + "("
out += RegExp.$2.replace(/([^, ]+\s+)+(\w+)/g, "$2")
out += ")"
out += RegExp.$3 || ''
}
if(/\.size/.test(out)){
out = out.replace(/\.size\(\)/,'.length');
}
if(/\/\s*2/.test(out)){
out = out.replace(/\/\s*2/,">>1");
}
if(/int|double|string/.test(out)){
out = out.replace(/int|double|string/,"var")
}
to.push(out);
}
return to.join("\n")
}
1 函数体内运算
1.1 lamda 表达式
[1,2,3].map(x=>x+1) //js
[x+1 for x in [1,2,3]] //python
1.2 解构赋值-交换
[ a , b ] = [ b, a+b ] //js
a , b = b, a+b //python
std::swap(a,b) //c++
1.3 运算符
&& || ! 'i>=0?a[i]:0'//js,c++
and or not 'a[i] if i>=0 else 0' //python
2 数组/List/vector操作
2.1 获取长度
a.length //js
len(a) //python
a.size() //c++
2.2 尾部 push 和 pop
a.push(1), b = a.pop() //js
a.append(1) , b = a.pop() //python
a.push_back(1), b=a.back();a.pop_back()//c++
2.3 排序
//升序 , 降序
a.sort((a,b)=>a-b) , a.sort((a,b)=>b-a)// js
a.sort(), a.sort(reverse=True) //python
std::sort(a.begin(),a.end()); std::sort(a.rbegin(),a.rend()) //c++
2.4 遍历
1. 拿到下标 2.拿到值
//js
for(let i in a) for(let i of a)
//python
for i in range(len(a)): for i in a:
//c++
int b[] = {2,6,5,4,3,1};
vector<int> a(b,b+6);
for(auto i = a.begin();i!=a.end();i++){
cout<< *i;
}
for(auto i : a){
cout<<i;
}
3 字符串操作
4 算法举例
4.1 简单快排=>快速搜索第 K 大数字
# js
function f(a,k){ return a.sort((a,b)=>b-a)[k-1] }
# python
class Solution:
def f(self, nums: 'List[int]', k: 'int') -> 'int':
nums.sort(reverse=True)
return nums[k-1]
# c++
class Solution {
public:
int f(vector<int>& nums, int k) {
std::sort(nums.rbegin(),nums.rend());
return nums[k-1];
}
};
4.2 手撸快排=>快速搜索第 K 大数字
# js
# 和 下面 C++的基本一致
# python
class Solution:
class Solution:
def findKthLargest(self, nums: 'List[int]', k: 'int') -> 'int':
l,r = 0,len(nums)-1
while l<=r:
p = self.partition(nums,l,r)
if p==k-1: return nums[p]
elif p>k-1: r = p-1
else: l = p+1
return -1
def partition(self,nums,l,r):
k = nums[l]
while l<r:
while l<r and nums[r]<=k:r=r-1
nums[l] = nums[r]
while l<r and nums[l]>=k:l=l+1
nums[r] = nums[l]
nums[r] = k
return l
# c++
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
int l=0,r=nums.size()-1;
while(l<=r){
int p = partition(nums,l,r);
if(p == k-1) return nums[p];
if(p<k-1) l = p+1;
else r = p-1;
}
return -1;
}
int partition(vector<int>&nums,int l, int r){
int k = nums[l];
while(l<r){
while(l<r && nums[r] <= k) r--;
nums[l] = nums[r];
while(l<r && nums[l] >= k) l++;
nums[r] = nums[l];
}
nums[l] = k;
return l;
}
};
网友评论