这个 向量::模板() 是一个C++中的STL,它通过在位置插入一个新元素来扩展容器。只有在需要更多空间时才会重新分配。这里的容器大小增加了一个。 语法:
null
template iterator vector_name.emplace (const_iterator position, element);
参数: 该函数接受以下两个强制参数:
- 位置 –它指定迭代器,该迭代器指向容器中要插入新元素的位置。
- 元素-指定要插入向量容器中的元素。
返回值: 该函数返回指向新插入元素的迭代器。
复杂性: 线性的 以下程序说明了上述功能: 项目1:
CPP
// C++ program to illustrate the // vector::emplace() function // insertion at thefront #include <bits/stdc++.h> using namespace std; int main() { vector< int > vec = { 10, 20, 30 }; // insert element by emplace function // at front auto it = vec.emplace(vec.begin(), 15); // print the elements of the vector cout << "The vector elements are: " ; for ( auto it = vec.begin(); it != vec.end(); ++it) cout << *it << " " ; return 0; } |
输出:
The vector elements are: 15 10 20 30
项目2:
CPP
// C++ program to illustrate the // vector::emplace() function // insertion at the end #include <bits/stdc++.h> using namespace std; int main() { vector< int > vec = { 10, 20, 30 }; // insert element by emplace function // at the end auto it = vec.emplace(vec.end(), 16); // print the elements of the vector cout << "The vector elements are: " ; for ( auto it = vec.begin(); it != vec.end(); ++it) cout << *it << " " ; return 0; } |
输出:
The vector elements are: 10 20 30 16
方案3:
CPP
// C++ program to illustrate the // vector::emplace() function // insertion at the middle #include <bits/stdc++.h> using namespace std; int main() { vector< int > vec = { 10, 20, 30 }; // insert element by emplace function // in the middle auto it = vec.emplace(vec.begin() + 2, 16); // print the elements of the vector cout << "The vector elements are: " ; for ( auto it = vec.begin(); it != vec.end(); ++it) cout << *it << " " ; return 0; } |
输出:
The vector elements are: 10 20 16 30
在数组V/s emplace()函数中使用shift操作进行常规插入 :
(a) 如果要在第一个索引和最后一个索引之间的某个特定位置插入一个元素,我们必须将该特定索引旁边的所有元素移动。所以,如果我们想保持代码的精确性 安放() 这是个不错的选择。依据 时间复杂性 两人都坐火车 相同线性时间 这直接取决于轮班操作的次数。
前任:
C++
#include <iostream> #include <vector> #include <array> using namespace std; int main() { array< int ,6> a={1,2,4,5}; vector< int > v={1,2,4,5}; // Insert 3 in the arr at index 2 for ( int i=3;i>=0;i--) { if (i!=1) a[i+1]=a[i]; else { a[i+1]=3; break ; } } // Time complexity is high cout<< "Content of a: " ; for ( int i=0;i<5;i++) cout<<a[i]<< " " ; v.emplace( v.begin() + 2 , 3); cout<< "Content of v: " ; for ( int i=0;i<v.size();i++) cout<<v[i]<< " " ; return 0; } |
输出
Content of a: 1 2 3 4 5 Content of v: 1 2 3 4 5
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END