📜  C++ STL-Multiset.count()函数

📅  最后修改于: 2020-10-20 01:17:50             🧑  作者: Mango

C++ STL Multiset.count()

C++ Multiset count()函数用于返回在容器中找到的元素数。由于Multiset容器不包含任何重复元素,因此,如果Multiset容器中存在值val的元素,则此函数实际上返回1,否则返回0。

句法

size_type count (const value_type& val) const;

参数

val:要在Multiset容器中搜索的值。

返回值

如果Multiset容器中存在值val的元素,则返回1,否则返回0。

复杂度

大小为对数。

迭代器有效性

没有变化。

数据竞争

容器被访问。

同时访问容器的元素是安全的。

异常安全

如果引发异常,则Multiset合中没有任何更改。

例子1

让我们看一个简单的示例,使用给定的键值搜索元素:

#include 
#include 

using namespace std;
 
int main()
{
    // initialize container
    multiset mp;
 
    // insert elements in random order
    mp.insert( 30 );
    mp.insert( 40 );
    mp.insert( 30 );
    mp.insert( 20);
    mp.insert( 50 );
 
    // checks if key 30 is present or not
    if (mp.count(30))
        cout << "The key 30 is present\n";
    else
        cout << "The key 30 is not present\n";
 
    // checks if key 100 is present or not
    if (mp.count(100))
        cout << "The key 100 is present\n";
    else
        cout << "The key 100 is not present\n";
 
    return 0;
}

输出:

The key 30 is present
The key 100 is not present

在上面的示例中,count()函数检查给定值。如果该元素存在于Multiset容器中,那么它将显示消息,指出存在该元素,否则不存在。

例子2

让我们看一个简单的示例来搜索多重集的元素:

#include 
#include 

using namespace std;

int main ()
{
  multiset mymultiset;
  char c;

  mymultiset = {'a', 'c', 'f'};

  for (c='a'; c<'h'; c++)
  {
    cout << c;
    if (mymultiset.count(c)>0)
      cout << " is an element of mymultiset.\n";
    else 
      cout << " is not an element of mymultiset.\n";
  }

  return 0;
}

输出:

a is an element of mymultiset.
b is not an element of mymultiset.
c is an element of mymultiset.
d is not an element of mymultiset.
e is not an element of mymultiset.
f is an element of mymultiset.
g is not an element of mymultiset.

在上面的示例中,使用count()函数在多重集中搜索“ a”至“ h”元素。

例子3

让我们看一个简单的示例来搜索Multiset中的键:

#include 
#include 

using namespace std;

int main(void) {

   multiset m = {'a','b','b','d'};
            
   if (m.count('a') == 1) {
       cout<< " 'a' is present in the multiset \n";
   }

   if (m.count('z') == 0) {
      cout << " 'z' is not present in the multiset" << endl;
   }

   return 0;
}

输出:

'a' is present in the multiset 
'z' is not present in the multiset

在上面的示例中,键“ a”存在于多重集m中,因此它将是“ a”的值,而键“ z”不存在于多重集m中,因此没有值“ z”。

例子4

让我们看一个简单的例子:

#include   
#include   
  
int main()  
{  
    using namespace std;  
    multiset s1;  
    multiset::size_type i;  
  
    s1.insert(1);  
    s1.insert(1);  
  
    // Keys must be unique in multiset, so duplicates are ignored  
    i = s1.count(1);  
    cout << "The number of elements in s1 with a sort key of 1 is: "  
         << i << "." << endl;  
  
    i = s1.count(2);  
    cout << "The number of elements in s1 with a sort key of 2 is: "  
         << i << "." << endl;  
}

输出:

The number of elements in s1 with a sort key of 1 is: 1.
The number of elements in s1 with a sort key of 2 is: 0.