実験してみる。

ソースコード。


$ cat stdmaptest.cpp 
#include <iostream>
#include <sstream>
#include <string>
#include <map>
 
std::string int_to_string(int x){
  std::stringstream ss;
  ss << x;
  return ss.str();
}
 
int main(void){
  std::string str = "Hello, Goodbye.";
  typedef std::map<std::string, std::string> Props;
  Props myprops;
  for(int i=0; i<str.size(); i++){
    std::string key = str.substr(i, 1);
    std::string val = int_to_string(i);
    myprops[key] = val;
  }
  for(Props::iterator i=myprops.begin(); i!=myprops.end(); i++){
    std::string key = (*i).first;
    std::string val = (*i).second;
    char code = key[0];
    std::cout << key << "[" << (int)code << "] = " << val << std::endl;
  }
  return 0;
}

実行結果。


$ g++ stdmaptest.cpp 
 
$ ./a.out 
 [32] = 6
,[44] = 5
.[46] = 14
G[71] = 7
H[72] = 0
b[98] = 11
d[100] = 10
e[101] = 13
l[108] = 3
o[111] = 9
y[121] = 12

キーが文字列 std::string だと、イテレータがキーの昇順になってるように見える。

ちなみに、今回の環境。


$ uname -mrsv
Darwin 11.4.2 Darwin Kernel Version 11.4.2: Thu Aug 23 16:25:48 PDT 2012; root:xnu-1699.32.7~1/RELEASE_X86_64 x86_64
 
$ g++ --version
i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)
Copyright (C) 2007 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

手元にある書籍『C++ 標準ライブラリ チュートリアル&リファレンス』で調べてみたら載ってた。キーのソート方法を指定することができる。200~201ページ。

書籍『C++ 標準ライブラリ チュートリアル&リファレンス』

書籍『C++ 標準ライブラリ チュートリアル&リファレンス』

書籍『C++ 標準ライブラリ チュートリアル&リファレンス』

Ref.

tags: cpp

Posted by NI-Lab. (@nilab)