一个跟踪插入顺序的 std::map ?

新手上路,请多包涵

我目前有一个 std::map<std::string,int> 将一个整数值存储到一个唯一的字符串标识符中,我确实使用该字符串进行查找。它主要做我想要的,除了它不跟踪插入顺序。因此,当我迭代地图以打印出值时,它们会根据字符串进行排序;但我希望它们根据(第一次)插入的顺序进行排序。

我考虑过使用 vector<pair<string,int>> 代替,但我需要查找字符串并将整数值递增约 10,000,000 次,所以我不知道 std::vector 是否会明显变慢.

有没有办法使用 std::map 或者是否有另一个 std 容器更适合我的需要?

我在 GCC 3.4 上,我的 std::map 中的值可能不超过 50 对。

原文由 polyglot 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
1 个回答

无需 使用单独的 std::vector 或任何其他容器来跟踪插入顺序。你可以做你想做的,如下所示。如果您想保留广告订单,则可以使用以下程序(版本 1):

版本 1 :使用 std::map<std::string,int>插入顺序 计算唯一字符串

#include <iostream>
#include <map>
#include <sstream>
int findExactMatchIndex(const std::string &totalString, const std::string &toBeSearched)
{
    std::istringstream ss(totalString);
    std::string word;
    std::size_t index = 0;
    while(ss >> word)
    {
        if(word == toBeSearched)
        {
            return index;
        }
        ++index;
    }
    return -1;//return -1 when the string to be searched is not inside the inputString
}
int main() {
    std::string inputString = "this is a string containing my name again and again and again ", word;

   //this map maps the std::string to their respective count
    std::map<std::string, int> wordCount;

    std::istringstream ss(inputString);

    while(ss >> word)
    {
        //std::cout<<"word:"<<word<<std::endl;
    wordCount[word]++;
    }

    std::cout<<"Total unique words are: "<<wordCount.size()<<std::endl;

    std::size_t i = 0;

    std::istringstream gothroughStream(inputString);

    //just go through the inputString(stream) instead of map
    while( gothroughStream >> word)
    {
        int index = findExactMatchIndex(inputString, word);


        if(index != -1 && (index == i)){
         std::cout << word <<"-" << wordCount.at(word)<<std::endl;

        }
        ++i;
    }

    return 0;
}

上述 程序 的输出如下:

 Total unique words are: 9
this-1
is-1
a-1
string-1
containing-1
my-1
name-1
again-3
and-2

请注意,在上述程序中,如果您有逗号或任何其他分隔符,则它被视为一个单独的单词。例如,假设您有字符串 this is, my name is 然后字符串 is, 的计数为 1,而字符串 is is, 计数为 1。 ---is 是不同的。这是因为计算机不知道我们对 单词 的定义。

笔记

上面的程序是我对 如何在这个嵌套的 for 循环中按顺序输出数组中的字符的答案的修改? 以下为第 2 版:

版本 2 :使用 std::map<char, int>插入顺序 计算唯一字符

#include <iostream>
#include <map>
int main() {
    std::string inputString;
    std::cout<<"Enter a string: ";
    std::getline(std::cin,inputString);
    //this map maps the char to their respective count
    std::map<char, int> charCount;

    for(char &c: inputString)
    {
        charCount[c]++;
    }

    std::size_t i = 0;
    //just go through the inputString instead of map
    for(char &c: inputString)
    {
        std::size_t index = inputString.find(c);
        if(index != inputString.npos && (index == i)){
         std::cout << c <<"-" << charCount.at(c)<<std::endl;

        }
        ++i;
    }
    return 0;
}

在这两种情况/版本中, 无需 使用单独的 std::vector 或任何其他容器来跟踪插入顺序。

原文由 Jason Liam 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题