LoginSignup
1
1

More than 5 years have passed since last update.

C++覚え書き

Last updated at Posted at 2015-03-02

C++コーディングで良く忘れる項目を覚え書き。

クラス名の取得

CA *pt = new CA(); 
const std::type_info &info = typeid(*pt);
printf ("class - %s", info.name());

可変引数(※長さ制限有り)

std::string format(const char *fmt, ...) {
#define CC_MAX_STRING_LENGTH (1024*100)

  std::string ret;
  va_list ap;
  va_start(ap, fmt);

  char* buf = (char*)malloc(CC_MAX_STRING_LENGTH);
  if (buf != nullptr) {
    vsnprintf(buf, CC_MAX_STRING_LENGTH, fmt, ap);
    ret = buf;
    free(buf);
  }
  va_end(ap);
  return ret;
}

std::function

#include <function>

void CA::foo(std::function<void (int)> func) {
  func(100);
}

void CA::bar() {
  foo([this](int val){
    printf("val - %d", val);
  });
}

std::vector

#include <vector>

CA *ca1 = new CA();
CA *ca2 = new CA();

std::vector<CA*> list;

// 追加
list.push_back( ca1 );
list.push_back( ca2 );

// まとめて代入
list = {ca1, ca2};

// イテレータアクセス
for (std::vector<CA*>::iterator it=list.begin(); it!=list.end(); ++it) {
  CA *ca = *it;
}

// 特定項目の削除
list.erase( remove(list.begin(), list.end(), ca1), list.end() );

std::map

#include <map>

std::map<std::string, int> maps;

// 追加
maps["1st"] = 100;
maps["2nd"] = 200;

// まとめて代入
maps = {{"1st", 100}, {"2nd", 200}};

// 順次アクセス
for (std::vector<std::string, int>::iterator it=maps.begin(); it!=maps.end(); ++it) {
  std::string key = it->first;
  int val = it->second;
  printf ("key=%s, val=%d", key.c_str(), val);
}

// 要素の検索
if (maps.find("2nd") != maps.end()) {
  printf ("要素が見つかった");
}

// 特定項目の削除
maps.erase("2nd");

1
1
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
1
1