在向量数组中的元素比较元素 [英] Compare element in a vector with elements in an array
问题描述
我有两个数据的数据结构在其中。
- 一个是一个vector
的std ::矢量<&INT GT; presentStudents
键,另一个是 -
字符
阵列字符cAllowedStudents [256];
现在我要比较这两个这样的检查在矢量
对阵列
,使得所有元素的每一个元素在载体应该是阵列中的present否则我将返回假
如果在这不是阵列的一部分向量的元素。
我想知道这样做的最有效,最简单的解决方案。我可以我的 INT载体
转换成字符数组
,然后比较一个接一个,但是这将是冗长的操作。是否有实现这一目标的一些更好的办法?
- 排序
cAllowedstudents
使用的std ::排序
。 - 遍历
presentStudents
,并查找在排序cAllowedStudents
使用<$ C $每名学生C>的std :: binary_search 。 - 如果你没有找到矢量的项目,返回false。
- 如果发现向量的所有元素,返回true。
下面是一个函数:
布尔检查()
{
//假设后有机会获得cAllowedStudents
从功能和// presentStudents。 字符* CEND = cAllowedStudents + 256;
的std ::排序(cAllowedStudents,CEND); 的std ::矢量&lt;&INT GT; ::迭代器ITER = presentStudents.begin();
的std ::矢量&lt;&INT GT;:迭代结束= presentStudents.end();
为(;!ITER =结束++ ITER)
{
如果(!(的std :: binary_search(cAllowedStudents,CEND,* ITER)))
{
返回false;
}
}
返回true;
}
另一种方法,使用的std ::差异
。
布尔检查()
{
//假设后有机会获得cAllowedStudents
从功能和// presentStudents。 字符* CEND = cAllowedStudents + 256;
的std ::排序(cAllowedStudents,CEND); 的std ::矢量&lt;&INT GT;差异;
的std :: set_difference(presentStudents.begin(),presentStudents.end()
cAllowedStudents,CEND,
的std :: back_inserter(差异));
回报(diff.size()== 0);
}
I have two data structures with data in them.
- One is a vector
std::vector<int> presentStudents
And other is a char
arraychar cAllowedStudents[256];
Now I have to compare these two such that checking every element in vector
against the array
such that all elements in the vector should be present in the array or else I will return false
if there is an element in the vector that's not part of the array.
I want to know the most efficient and simple solution for doing this. I can convert my int vector
into a char array
and then compare one by one but that would be lengthy operation. Is there some better way of achieving this?
- Sort
cAllowedstudents
usingstd::sort
. - Iterate over the
presentStudents
and look for each student in the sortedcAllowedStudents
usingstd::binary_search
. - If you don't find an item of the vector, return false.
- If all the elements of the vector are found, return true.
Here's a function:
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;
}
Another way, using 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);
}
这篇关于在向量数组中的元素比较元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!