LoginSignup
3
0

More than 1 year has passed since last update.

Python と c++ の文法の比較

Last updated at Posted at 2022-11-01

私が c++ の使い方を忘れないようにまとめておくのが主な目的です.頑張って拡充していきます.

入力

整数の入力

n=int(input())
int n;
cin>>n;

配列の入力

A=list(map(int,input().split()))
vector<int> A(N);
for(int i=0;i<N;i++){
  cin>>A.at(i);
}

A.at(i)A[i] でもいいらしい.

入力高速化のおまじない

from sys import stdin
input=lambda :stdin.readline()[:-1]

コードの先頭に書く.

ios::sync_with_stdio(false);
cin.tie(nullptr);

main 関数の先頭に書く.

出力

小数を桁数を指定して出力

print('{:.10f}'.format(x))
cout << fixed << setprecision(10);

※ main 関数の先頭に書く

配列

要素の追加

A.append(x)
A.push_back(x)

配列の結合

A+=B

※ リスト A の末尾にリスト B を結合する

A.insert(A.end(),B.begin(),B.rend())

※ vector A の末尾に vector B を結合する

配列の反転

A.reverse()

A=A[::-1]
reverse(A.begin(),A.end())

2 次元配列の作成

A=[[0]*W for i in range(H)]
vector<vector<int>> A(H,vector<int>(W,0));

文字列

整数を文字列に変換

str(n)

※ n は int 型

to_string(n)

※ n は int 型

for 文

for 文

for i in range(N):
for(int i=0;i<N;i++)

配列の走査

for i in A:

for x,y in xy:
for(auto i:A)

for(auto [x,y]:xy)

※ xy は pair 型の配列

set

要素が存在するか判定

x in S

※ S は set 型

S.count(x)

※ S は set/unordered_set 型

要素の走査

for x in S:

※ S は set 型

for(auto x:S)

※ S は set/unordered_set 型

連想配列

連想配列の走査

for key,value in dic:

※ dic は dict 型

for(auto [index,value]:dic)

※ dic は map/unordered_map 型

ソート

普通のソート

A.sort()
sort(A.begin(), A.end())

降順ソート

A.sort(revese=True)
sort(A.rbegin(), A.rend())

ペア型のソート

xy.sort(key=lambda x:x[1])
sort(xy.begin(), xy.end(), [](pair<int, int> A, pair<int, int> B){ return A.second < B.second; });

※ xy は pair 型の配列
※ c++ のラムダ式については https://t.co/ZybRlJsNiZ

bool cmp(pair<int,int> a,pair<int,int> b){
  return a.second<b.second;
}
sort(xy.begin(),xy.end(),cmp);

重複を除いてソート

A=sorted(list(set(A)))
sort(A.begin(),A.end());
A.erase(unique(A.begin(),A.end()),A.end());

優先度付きキュー

from heapq import heappop,heappush
hq=[]
heappush(hq,x) # 要素の追加
hq[0] # 最小値を取得
heappop(hq) # 最小値を削除(しながら取得)
len(hq) # 要素数を取得
priority_queue<int,vector<int>>pq;
pq.push(x) // 要素の追加
hq.top() // 最大値を取得
hq.pop() // 最大値を削除
hq.size() // 要素数を取得

python はデフォルトが昇順,c++ はデフォルトが降順になっている.c++ で昇順にしたい場合は

priority_queue<int,vector<int>,greater<int>>pq;

のように greater を加えると良い.

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0