0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MFC(VC++)で配列を扱うなら、どれ🤔

Last updated at Posted at 2019-11-25

前提

  • MFCでWin32 デスクトップアプリケーションを作成している
  • Visual Studio 2017で、ツールセットはv141を使用している(C++14までサポートされているかな?たしか。)

記事の動機

コードレビューをしていると、チーム内でのコーディングにバラツキを感じることがありますよね。つかっている言語によるところが大きいとおもっているのですが、C++はとくに大きいと感じます。

配列の扱い方

おおきくわけるとこの3つから選択することになります。

  1. [ ]で頑張る
  2. MFCだからCArray
  3. STLが使える状況ならstd::vector

今回は、構造体の配列を管理し、特定の条件にマッチする要素を取り出すを例にしてみます。

1. [ ]で頑張る

// DATA
struct Item
{
  int nId;
  int nPrice;
};


// 1. 
const Item items[] = {
  { 0, 100 },
  { 1, 1000 },
  { 2, 10000 },
};

int GetPriceById(int id) {
  const int max = sizeof(items)/sizeof(struct Item);
  for (int i=0; i<max; i++) {
    if( items[i].nId == id ){
      return items[i].nPrice;
    }
  }
  return -1;
}

2. MFCだからCArray

10年やっても書き馴染まないのでサンプル書けない :thumbsup:

3. STLが使える状況ならstd::vector

// 3.  
# include <vector>
# include <algorithm>
const std::vector<Item> items {
  { 0, 100 },
  { 1, 1000 },
  { 2, 10000 },
};

int GetPriceById(int id) {
  auto it = std::find_if(items.begin(), items.end(), [](const Item& item) {
    return item.nId == id;
  });
  return ( it == items.end() )? -1 : it->nPrice;
}

個人的にstd::vectorを推していきたい

  • サイズを意識したくない
  • 多くの、便利で、よくテストされた、ライブラリが使用できる(<[algorithm](https://en.cppreference.com/w/cpp/header/algorithm)>)
  • 動的配列もラクに実装できるし、constすれば静的配列としても扱えるしラク。
  • 記述を少なくループを回せてラク。for (auto item : items)

とにかくラク。これに尽きます。

生配列は「使わざるを得ない」場合だけ

DLLとのインターフェース部分とか、STLを使ってはいけない環境のときだけ仕方なく使います。

おわりに

素朴なC++の構文はレゴブロックの1ピースのようなもので、「組み方ひとつでいかようにも」と同時に、「労多く実り少ない」という一面もあるので実装スピードや後々のコードを読む時間を考えるとSTLのようなライブラリを活用して型安全でリーダブルなコードを増やしていくのがよいのではないかと考えています。というポエムでこの記事を終わります。

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?