比较vector中的元素与数组中的元素

Compare element in a vector with elements in an array

本文关键字:元素 数组 vector 比较      更新时间:2023-10-16

我有两个包含数据的数据结构。

  • 一个是矢量std::vector<int> presentStudents,另一个是
  • char array char cAllowedStudents[256];

现在我必须比较这两个,以便检查vector中的每个元素与array,这样向量中的所有元素都应该出现在数组中,否则如果向量中有一个元素不是数组的一部分,我将返回false

我想知道做这件事最有效和最简单的解决方案。我可以将我的int vector转换成char array,然后逐一比较,但这将是冗长的操作。有没有更好的方法来实现这个目标?

我建议您使用散列映射(std::unordered_map)。将char数组的所有元素存储在哈希映射中。

然后依次检查vector中的每个元素是否存在于O(1)中的映射中。

Total time complexity O(N), extra space complexity O(N).

注意,你必须在编译器中启用c++ 11。

请参考c++算法头文件中的set_difference()函数。您可以直接使用此函数,并检查结果diff set是否为空。如果不为空则返回false。

一个更好的解决方案是调整set_difference()的实现,就像这里:http://en.cppreference.com/w/cpp/algorithm/set_difference,在获得第一个不同的元素后立即返回false。

适应例子:

while (first1 != last1)
{
    if (first2 == last2) 
        return false;
    if (*first1 < *first2)
    {
        return false;
    }
    else
    {
        if (*first2 == *first1)
        {
            ++first1;
        }
        ++first2;
    }
}
return true;
  1. 使用std::sort排序cAllowedstudents
  2. 遍历presentStudents,并使用std::binary_search查找排序后的cAllowedStudents中的每个学生。
  3. 如果没有找到向量的项,返回false。
  4. 如果找到向量的所有元素,返回true。

这是一个函数:

bool check()
{
   // Assuming hou have access to cAllowedStudents
   // and presentStudents from the function.
   char* cend = cAllowedStudents+256;
   std::sort(cAllowedStudents, cend);
   std::vector<int>::iterator iter = presentStudents.begin();
   std::vector<int>::iterator end = presentStudents.end();
   for ( ; iter != end; ++iter )
   {
      if ( !(std::binary_search(cAllowedStudents, cend, *iter)) )
      {
         return false;
      }
   }
   return true;
}

另一种方法,使用std::difference .

bool check()
{
   // Assuming hou have access to cAllowedStudents
   // and presentStudents from the function.
   char* cend = cAllowedStudents+256;
   std::sort(cAllowedStudents, cend);
   std::vector<int> diff;
   std::set_difference(presentStudents.begin(), presentStudents.end(),
                       cAllowedStudents, cend,
                       std::back_inserter(diff));
   return (diff.size() == 0);
}

用std:: Sort对两个列表进行排序,并在数组上迭代使用std::find。

编辑:技巧是使用先前找到的位置作为下一次搜索的开始。

std::sort(begin(pS),end(pS))
std::sort(begin(aS),end(aS))
auto its=begin(aS);
auto ite=end(aS);
for (auto s:pS) {
    its=std::find(its,ite,s);
    if (its == ite) {
        std::cout << "Student not allowed" << std::cout;
        break;
    }
}

编辑:正如传说中提到的,通常使用二进制搜索可能更有效(如R Sahu的答案)。然而,对于小型数组,如果向量包含数组中很大一部分的学生(我认为至少十分之一),那么二进制搜索的额外开销可能(也可能不会)超过其渐近复杂性的好处。

使用c++ 11。在您的示例中,size是256。请注意,我个人没有测试过它,甚至没有将它放入编译器中。然而,它应该会给你一个好主意,让你知道自己该怎么做。我强烈建议用这个来测试边缘情况!

#include <algorithm>
bool check(const std::vector<int>& studs, 
char* allowed, 
unsigned int size){
    for(auto x : studs){
        if(std::find(allowed, allowed+size-1, x) == allowed+size-1 && x!= *(allowed+size))
            return false;
    }
    return true;
}