Skip to content

283. Move Zeroes#3

Open
usatie wants to merge 4 commits into
review-basefrom
283/move-zeroes
Open

283. Move Zeroes#3
usatie wants to merge 4 commits into
review-basefrom
283/move-zeroes

Conversation

@usatie

@usatie usatie commented Jan 31, 2025

Copy link
Copy Markdown
Owner

問題 : https://leetcode.com/problems/move-zeroes
言語 : C++
step3をやる際に、念の為ローカルでテストができるようにmain.cppとMakefileも用意しています。
今回はstd::initializer_listを使用してテストを書いてみました。(前回は #2 可変引数マクロを利用)

Comment thread Arai60/44. Move Zeroes/step3.hpp Outdated
Comment on lines +6 to +7
using std::iter_swap;
using std::vector;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ヘッダーファイル内での using は include したところが全部影響を受けるので避けましょう。

num`という書き方もできるけど, error-proneなのでやめた
2. Iteratorを使わない場合はswapしたいので、numがreferenceとなるよう注意
3. 0埋めをあとで行うのは,
filterしたい値が1つだけの場合に有効だが、複数の値をたとえば移動したい場合とかは順番もretainできるしswapがよいかな

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

いいと思います。
あとは、Erase-Remove Idiom というのがあることくらいですかね。
https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0#heading=h.v62rdhwkdymb

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

なるほどー。この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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

forやifの後の{}をつけている場合やつけていない場合がございますが統一した方がいいかと思いました。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ありがとうございます。これは(好きではないのですが短いかなと思って)for-if文をone-linerで書くのを試した痕なのですが、commit前にclang-formatで改行されてしまっていたみたいです。気づきませんでした。

public:
// 1. swapを使う
void moveZeroes1(vector<int> &nums) {
auto next_pos = nums.begin();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

変数名の単語はフルスペルで書いたほうが読みやすいと思うのですが、この規模であれば問題ないような気もしました。

@usatie usatie changed the title 283/move zeroes 283. Move Zeroes Feb 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants