283. Move Zeroes#3
Conversation
| using std::iter_swap; | ||
| using std::vector; |
There was a problem hiding this comment.
ヘッダーファイル内での using は include したところが全部影響を受けるので避けましょう。
| num`という書き方もできるけど, error-proneなのでやめた | ||
| 2. Iteratorを使わない場合はswapしたいので、numがreferenceとなるよう注意 | ||
| 3. 0埋めをあとで行うのは, | ||
| filterしたい値が1つだけの場合に有効だが、複数の値をたとえば移動したい場合とかは順番もretainできるしswapがよいかな |
There was a problem hiding this comment.
いいと思います。
あとは、Erase-Remove Idiom というのがあることくらいですかね。
https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0#heading=h.v62rdhwkdymb
There was a problem hiding this comment.
なるほどー。このwikiを読んでよく理解できました。これが常識なんですね。
https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom
これを知っていたら、今回の例ならFill-Remove Idionとして書くことが真っ先に思い浮かびそうですね。
std::fill(std::remove(nums.begin(), nums.end(), 0), nums.end(), 0);
| // 2-2. for/if文をOne-linerっぽく書く (error-proneなので好きではない) | ||
| void moveZeroes22(vector<int> &nums) { | ||
| auto next_pos = nums.begin(); | ||
| for (auto num : nums) |
There was a problem hiding this comment.
forやifの後の{}をつけている場合やつけていない場合がございますが統一した方がいいかと思いました。
There was a problem hiding this comment.
ありがとうございます。これは(好きではないのですが短いかなと思って)for-if文をone-linerで書くのを試した痕なのですが、commit前にclang-formatで改行されてしまっていたみたいです。気づきませんでした。
| public: | ||
| // 1. swapを使う | ||
| void moveZeroes1(vector<int> &nums) { | ||
| auto next_pos = nums.begin(); |
There was a problem hiding this comment.
変数名の単語はフルスペルで書いたほうが読みやすいと思うのですが、この規模であれば問題ないような気もしました。
問題 : https://leetcode.com/problems/move-zeroes
言語 : C++
step3をやる際に、念の為ローカルでテストができるようにmain.cppとMakefileも用意しています。
今回はstd::initializer_listを使用してテストを書いてみました。(前回は #2 可変引数マクロを利用)