如何在地图中插入对象,使其保持排序状态

时间:2017-11-09 10:41:25

标签: c++

嗨我正在研究一个c ++程序,将某些具有字符串作为属性的对象插入到地图中。如何插入对象,保持按字母顺序排序

下面的代码是vector的示例代码。我需要使用map

实现相同的功能
    Word *WordVector::insert(const string text){
    Word newWord(text);
    if(data.size()==0)
    {
        data.push_back(newWord);
    }

    else{
        auto insert_itr = std::lower_bound(data.begin(), data.end(),newWord);
        if(insert_itr==data.end()||*insert_itr!=newWord){
            data.insert(insert_itr, newWord);
        }
        else newWord.increaseCount();
    }
    return &newWord;
}

我是c ++的新手所以请原谅我是否有愚蠢的错误。感谢您提前提供任何帮助。

此代码也给了我一个大于预期的矢量大小。任何见解都会有所帮助:)

1 个答案:

答案 0 :(得分:0)

看起来你只需要std::map<std::string, int>

class WordContainer
{
    std::map<std::string, int> words;
    public:
    void insert(const std::string & text)
    {
        ++words[text];
    }
    int count(const std::string & text)
    {
        return words[text];
    }
}

有关如何制作新类型地图的原始文字:

让我们想象你有一个&#39; struct Thing&#39 ;,例如

struct Thing
{
    std::string name; // We need to keep Things in alphabetical order by name
    int other_member; // etc
};

现在,如果我们尝试使用这样的std::map<Thing, T>,我们将收到编译错误,例如:

/usr/local/include/c++/7.2.0/bits/stl_function.h:386:20: error: no match for 'operator<' (operand types are 'const Thing' and 'const Thing')
       { return __x < __y; }
                ~~~~^~~~~

这是因为我们尚未在地图中指定如何订购Thing,而使用<的默认设置并未找到Thing的匹配项s。或者。

所以我们需要进行比较:

struct Thing_less
{
    bool operator()(const Thing & lhs, const Thing & rhs)
    {
        return lhs.name < rhs.name;
    }
}

我们将此作为map类型的一部分使用:

int main() {
    std::map<Thing, double, Thing_less> things;
    things[{ "First", 1 }] = 1.5;
    things[{ "Second", 2 }] = 3.14;
    things[{ "Third", 3 }] = 0.0;
    things[{ "Forth", 4 }] = 100.1;

    for (auto & pair : things)
    {
        std::cout << pair.first.name << pair.second << "\n";
    }

    return 0;   
}

我们得到了结果:

First 1.5
Forth 100.1
Second 3.14
Third 0