vector :: emplace()是C++中的STL,它通过在位置插入新元素来扩展容器。仅当需要更多空间时才进行重新分配。在这里,容器尺寸增加了一个。
句法:
template
iterator vector_name.emplace (const_iterator position, element);
范围:
该函数接受两个强制性参数,分别指定如下:
- position –指定迭代器,该迭代器指向容器中要插入新元素的位置。
- args –它指定要插入到矢量容器中的要插入的元素。
返回值:该函数返回一个迭代器,该迭代器指向新插入的元素。
下面的程序说明了上述函数:
程序1:
// C++ program to illustrate the
// vector::emplace() function
// insertion at thefront
#include
using namespace std;
int main()
{
vector 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:
// C++ program to illustrate the
// vector::emplace() function
// insertion at the end
#include
using namespace std;
int main()
{
vector 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:
// C++ program to illustrate the
// vector::emplace() function
// insertion at the middle
#include
using namespace std;
int main()
{
vector 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
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。