附加到其中包含 set<size_t> 的映射

Appending to map with set<size_t> in it

嘿,我的导师(有点)给了我这个任务,我很难解决它。

所以基本上我 const vector<string> &data 充满了字符串,我需要检查它们的位置,比如它们在那个向量中的什么位置,所以这里有一个例子:

获取输入:data={"chair","desk","table","chair","chair","desk"}

我的输出应该是:{"chair" ->{0,3,4},"desk"->{1,5} , "table"->{2}}

所以我所做的是:

 map<string, set<size_t>> index(const vector<string> & data) noexcept {
    
        map<string, set<size_t>> res;  // thats gon be my return
       
        if (data.empty()){
            return res;
        }
        for (auto it = data.begin(); it != data.end(); it++) {
         
           if(res.find(*it)==res.end()){


            //so basically when we are the first ,  and nothing is there so 
            // it should insert  for example =chair , and a 0 


                res.insert(std::make_pair(*it, 0));   // i tried it like that it doesnt work 
           }else{
                // when the string "chair is already in there  i want to append to the set  the current index where we are and thats what i dont know how
    
    
    
        }
}

    return res;
}

如何获取当前字符串的索引并将其附加到我的集合,以便如前所述那样工作?

您可以使用基于索引的循环很容易地实现这一点:

map<string, set<size_t>> index(const vector<string> & data) 
{    
    map<string, set<size_t>> res; 

    for (std::size_t i = 0u; i < data.size(); ++i)
        res[ data[i] ].insert(i);
      //    ^string^          ^index

    return res;
}
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>

std::map<std::string, std::set<size_t>> index(const std::vector<std::string>& data) noexcept 
{
    std::map<std::string, std::set<size_t>> res;
    for (size_t idx = 0u; idx < data.size(); idx++) 
    {
        res[data[idx]].insert(idx);
    }
    return res;        
}

int main()
{
   const std::vector<std::string> data={"chair","desk","table","chair","chair","desk"};
   auto map = index(data);

   for( auto it = map.begin(); it != map.end(); ++it )
   {
      std::cout << (*it).first << " ->";
      for( auto it_id = (*it).second.begin(); it_id != (*it).second.end(); it_id++)
      {
        std::cout << " " << *it_id;
      }
      std::cout << "\n";
   }
}

所以你的问题可以用 oneline 解决,如索引函数所示 - 但为什么呢?

您将所有这些不同的 std 容器类型作为输入是有原因的 - 它们中的每一个都有一些保证,可以在文档中查找。

向量元素在内存中是连续的(序列容器)。

而 map 和 set 是关联的并且具有唯一键。

查阅容器属性的文档(我链接到矢量 - 但其余的也存在于左侧的树中)。 http://www.cplusplus.com/reference/vector/vector/

教训是知道使用哪个工具(容器)来解决特定任务

一旦你确定了 .. 确保项目是唯一的或者如何对向量中的每个奇数元素进行排序应该是一件轻而易举的事。