c++ - 如何在指针中保存 vector 元素的详细信息?

标签 c++ pointers vector

我正在尝试比较 2 个二维 vector ,这两个 vector 每 52 行内包含 10 个单元格。我正在尝试比较前 5 行作为引用,然后将所有其他行与这 5 行进行比较,然后最重要的是保存所有信息(引用 ID 和单元格的位置),这些信息正是找到了引用单元格的哪个单元格与每行的哪些细胞相似。在引用单元格中找不到的单元格应按原样打印。这是我试过的:

int main(){
    vector <vector<string>> reference_one_cell;   /*stored all the cells of 5 reference lines */
    vector < vector<string> > input_array;    /*stored all the cells all 52  lines  */

                  /*comparison part*/   

          std::set<std::string> stringSet;
          for ( auto const& vs : reference_one_cell)
          for ( auto const& item : vs )
           stringSet.insert(item);

                 for (int f=0;f<52;f++){
                  for (int g=0;g<10;g++){

                    bool found = any_of(stringSet.begin(),
                                 stringSet.end(),
                                  [=](std::string const& item){return input_array[f][g] == item;});
                     if ( found )
                     {

                        outputFile << ",";
                     }
                     else
                     {

                        outputFile<<input_array[f][g];
                     }
                  }

               }

  }     

我能够为在引用行中找到的单元格打印出“,”。但是几天来我一直在思考如何使用 pointerpair 来存储我可以返回到的所有详细信息(引用 id 和引用线中的位置)又是原来的状态。提前致谢

最佳答案

  1. 添加一个变量来跟踪找到匹配项的 reference_one_cell 的索引。

    std::vector<std::pair<std::size_t, std::size_t>> indices;
    
  2. 确保在找到匹配项后更新 indices 的内容。

  3. 在最外层循环结束后使用索引


int main(){

   ... 

   // Variable to keep track of matching indices.
   std::vector<std::pair<std::size_t, std::size_t>> indices;

   ...

   for (int f=0;f<52;f++){
      for (int g=0;g<10;g++){

         bool found = any_of(stringSet.begin(),
                             stringSet.end(),
                             [=](std::string const& item){return input_array[f][g] == item;});
         if ( found )
         {
            // Use more elaborate but explicit code.
            // indices.push_back(std::pair<std::size_t, std::size_t>{f, g});

            // Or use succinct but not so explicit code.
            indices.push_back({f, g});

            outputFile << ",";
         }
         else
         {
            outputFile<<input_array[f][g];
         }
      }
   }

   // Use indices

   ...
}

关于c++ - 如何在指针中保存 vector 元素的详细信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44016493/

相关文章:

c++ - 从 ß 转换为 s c++

c++ - 如何调用返回指针数组的函数? C++

c++ - 函数指针演示

c++ - 堆栈内存/堆栈

c++ - 如何创建节点结构类型的 Min STL priority_queue

c++ - 我可以将 std::vector<int>* 转换为 int* 吗?

c++ - 为什么表达式 strlen(cstr1) 没有计算为常量,其中 cstr1 是一个 const char 数组?

c++ - 在数组索引中将变量递增 N

c++ - 在函数模板中的类型之间转换

c++ - 如何将指向指针数组的指针作为参数传递给函数?