我使用的std ::地圖這樣的方式:C++的std ::地圖<的std :: string,int>的獲取值,其鍵開始與一個特定的字符串
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
map<string, int> my_map;
my_map.insert(pair<string, int>("Ab", 1));
my_map.insert(pair<string, int>("Abb", 2));
my_map.insert(pair<string, int>("Abc", 3));
my_map.insert(pair<string, int>("Abd", 4));
my_map.insert(pair<string, int>("Ac", 5));
my_map.insert(pair<string, int>("Ad", 5));
cout<<my_map.lower_bound("Ab")->second<<endl;
cout<<my_map.upper_bound("Ab")->second<<endl;
return 0;
}
我想要獲得所有以特定字符串開頭的值(例如「Ab」)。我可以使用map :: lower_bound輕鬆獲得開始迭代器。但是我怎麼能得到一個上限?我是否必須從下限開始迭代整個集合,並檢查每個鍵是否仍以「Ab」開頭?
在這種特殊情況下'my_map.lower_bound(「Ac」)似乎是這樣做的 – 2013-04-28 12:55:35
爲什麼不能獲得「Ac」的界限? b和c之間沒有字母。 – stardust 2013-04-28 12:55:50
我需要更一般的方法。例子只是爲了描述問題。我可以是任何類型的字符串,並且map可以包含任何類型的字符串。 – Dejwi 2013-04-28 12:58:12