存储从字符串到整数的映射的最佳方法,以及另一种方式同时存储?

时间:2014-01-29 11:38:38

标签: c++ c++11

存储从字符串到整数的映射的最佳方法,反之亦然?

例如,我有一个名为columnNames的向量,我想 能够获得一个给出其索引的列名,即它的位置,但随后 我也希望得到它的名字。一种方法来做到这一点 是按顺序使用地图和存储列名,这样 我将能够做我想做的事,但我想知道是否有更好的方法?

4 个答案:

答案 0 :(得分:6)

取决于“更好”的意思。 Boost.MultiIndex是一种非常灵活的方式,可以做到这一点和其他类似的东西,而Boost.Bimap更专业。

对于这种特定情况,您可以使用map<string,int>vector<const string*>进行从索引到字符串的查找(因为索引本质上形成一个连续的序列)。向量中的指针指向地图中的键。如果您在设置后不修改列,这是最简单的,但即使您这样做,也可以更新vector以匹配。

答案 1 :(得分:3)

不知道C ++ 11中有什么东西,但这可能有效:

http://www.boost.org/doc/libs/1_46_1/libs/bimap/doc/html/index.html

  

Boost.Bimap是C ++的双向地图库。随着Boost.Bimap   您可以创建可以使用这两种类型的关联容器   作为关键。 bimap可以被认为是a的组合   std :: map和std :: map。 bimap的学习曲线是   如果你知道如何使用标准容器,几乎是平的。好的折扣   已经将努力用于映射STL的命名方案   Boost.Bimap。该库旨在匹配常见的STL   容器

一个(可能更糟的是,O(n))解决方案与lambdas:

#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <algorithm>
using namespace std;

map<string, int> m = {{"hello", 1}, {"world", 2}};



int main() {


    int findVal = 2;
    auto it = find_if(m.begin(), m.end(), [findVal](const pair<string,int> & p) {
        return p.second == findVal;
    });

    if(it != m.end())
        cout << it->second << "->" << it->first << "\n";

    string findStr = "hello";
    auto itStr = find_if(m.begin(), m.end(), [findStr](const pair<string,int> & p) {
        return p.first.compare(findStr) == 0;
    });

    if(itStr != m.end())
        cout << itStr->second << "->" << itStr->first << "\n";


    return 0;
}

如果你正在寻找非常简单的东西(也可能非常低效),请使用:

#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <algorithm>
using namespace std;

map<string, int> m = {{"hello", 1}, {"world", 2}};

class notFound
{ };

string findFromInt(const int& val)
{
    map<string,int>::iterator it = m.begin();
    while(it != m.end())
    {
        if(it->second == val)
            return it->first;

        it++;
    }
    throw new notFound();
}

int findFromString(const string& str)
{
    map<string,int>::iterator it = m.begin();
    while(it != m.end())
    {
        if(it->first.compare(str) == 0)
            return it->second;

        it++;
    }
    throw new notFound();
}


int main() {


    int findVal = 2;
    try {
        string str = findFromInt(findVal);

        cout << "found: " << str;
    } catch(notFound *obj) {
        cout << "Value not found";
    }


    string findStr = "hgggllo";
    try {
        int val = findFromString(findStr);

        cout << "found: " << val;
    } catch(notFound *obj) {
        cout << "Value not found";
    }




    return 0;
}

http://ideone.com/2FP64h

答案 2 :(得分:1)

在你的用例中,我更喜欢你提到的方法(map + vector)而不是bi-maps。 您的用例是特殊的,因为您的整数从零开始并且是连续的。

您提出的解决方案简单,高效(尤其是hashmap,aka.unordered_map + vector),并且不需要任何外部库。

答案 3 :(得分:0)

您可以使用双向地图,如下所示:

boost bimap

相关问题