C++ multiset size()
C++ multiset size()
C++ multiset size()函数用于查找 multiset 容器中存在的元素数。
语法
成员类型 size_type 是无符号整数类型。
size_type size() const; // until C++ 11
size_type size() const noexcept; //since C++ 11
参数
无
返回值
size()函数返回存在的元素数
复杂度
常量。
迭代器有效性
没有变化。
数据竞争
已访问容器。
同时访问 multiset 容器的元素是安全的。
异常安全性
此函数绝不会引发异常。
示例1
让我们看一个简单的示例来计算 multiset 的大小:
#include <set>
#include <iostream>
using namespace std;
int main()
{
multiset<char> num {'a', 'b', 'c', 'd', 'a'};
cout << "num multiset contains " << num.size() << " elements.\n";
return 0;
}
输出:
num multiset contains 5 elements.
在上面的示例中, multiset num包含5个元素。因此size()返回5个元素。
示例2
让我们看一个简单的示例,该示例计算元素集的初始大小和添加元素后元素集的大小:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
multiset<int> m;
cout << "Initial size of multiset = " << m.size() << endl;
m = {1,2,3,4,5,4};
cout << "Size of multiset after inserting elements = " << m.size() << endl;
return 0;
}
输出:
Initial size of multiset = 0
Size of multiset after inserting elements = 6
在上面的示例中,第一个 multiset 为空,因此,size()函数将返回0,并且在插入6个元素之后将返回6、
示例3
让我们看一个简单的例子:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
multiset<int> mymultiset = {100,200,300,400,200};
while (mymultiset.size())
{
cout << *mymultiset.begin()<< '\n';
mymultiset.erase(mymultiset.begin());
}
return 0;
}
输出:
在上面的示例中,它仅在while循环中使用size()函数并打印multiset的元素,直到multiset的大小为止。
示例4
让我们看一个简单的示例:
#include <iostream>
#include <set>
#include <string>
using namespace std;
int main() {
typedef multiset<int> marksMultiset;
int number;
marksMultiset marks;
cout<<"Enter three sets of marks: \n";
for(int i =0; i<3; i++)
{
cin>> number; // Get value
marks.insert(number); // Put them in multiset
}
cout<<"\nSize of marks multiset is:"<< marks.size();
cout<<"\nList of Marks: \n";
marksMultiset::iterator p;
for(p = marks.begin(); p!=marks.end(); p++)
{
cout<<(*p)<<" \n ";
}
return 0;
}
输出:
Enter three sets of marks:
340
235
340
Size of marks multiset is: 3
List of Marks:
235
340
340
在上面的示例中,程序首先以交互方式创建标记 multiset 。然后,它将显示标记 multiset 的总大小以及 multiset 中所有可用元素。