deque::assign 和 deque::empty 在C++中的区别
Deque或双端队列是一种序列容器,具有在两端扩展和收缩的特性。它们类似于向量,但在插入和删除末尾元素以及开头元素的情况下更有效。不像向量,连续存储分配可能无法保证。
在这里,我们将看到deque::assign和deque::at在C++中的区别。
deque::assign
deque::assign用于通过替换其当前内容来分配新内容到deque容器中。它会相应地改变大小。
语法:
dequename.assign(<int>size, <int>val)
参数:
- size– 要分配给容器的值的数量。
- val– 要分配给容器的值。
头文件:
<deque>
异常: 如果抛出异常,容器处于有效状态。
迭代器有效性: 在此容器中,所有迭代器,指针和引用都无效。
示例:
// C++ program to implement deque::assign
#include <deque>
#include <iostream>
using namespace std;
int main()
{
// Declaration of Deque
deque<int> d1 = { 1, 3, 6, 0, 0 };
deque<int> d2;
// Assigning d1 deque elements
// into d2 deque
d2.assign(d1.begin(), d1.end());
cout << "Elements in d2 container are : ";
for (auto it = d2.begin(); it != d2.end(); ++it){
cout << *it << " ";
}
cout << endl;
return 0;
}
输出
Elements in d2 container are : 1 3 6 0 0
- 时间复杂度 – O(N)
- 空间复杂度 – O(N)
deque::empty
deque::empty用于检查deque容器是否为空。它不会改变容器中的任何内容。
语法:
empty();
头文件:
<deque>
异常: 它永远不会抛出任何异常。
迭代器有效性: 此容器中的迭代器有效性不会更改。
示例:
// C++ program to implement deque::empty
#include <deque>
#include <iostream>
using namespace std;
int main()
{
// Declaration of Deque
deque<int> GFG = { 1, 3, 6, 0, 0 };
if (GFG.empty() == true){
cout << "The deque is empty" << endl;
}
else{
cout << "The deque is not empty" << endl;
}
return 0;
}
输出
The deque is not empty
- 时间复杂度 – O(1)
- 空间复杂度 – O(1)
deque::assign和deque::empty之间的区别
基础 | deque::assign | deque::empty |
---|---|---|
定义 | 用于为deque容器分配新内容。 | 用于检查deque是否为空。 |
语法 | dequename.assign(<int>大小,<int>值); |
empty() |
参数数量 | 只需要两个参数。 | 无 |
返回值 | 无 | 布尔值 |
复杂度 | 线性 | 常数 |