vector::emplace()是C++中的STL,它通過在位置插入新元素來擴展容器。僅當需要更多空間時才進行重新分配。在這裏,容器尺寸增加了一個。
用法:
template
iterator vector_name.emplace (const_iterator position, element);
參數:
該函數接受兩個強製性參數,分別指定如下:
- position-它指定迭代器,該迭代器指向容器中要插入新元素的位置。
- element-它指定要插入到向量容器中的要插入的元素。
返回值:該函數返回一個迭代器,該迭代器指向新插入的元素。
以下示例程序旨在說明上述函數:
程序1:
// 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:
// 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:
// 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
相關用法
- C++ unordered_set emplace()用法及代碼示例
- C++ list emplace()用法及代碼示例
- C++ unordered_multimap emplace()用法及代碼示例
- C++ unordered_multiset emplace()用法及代碼示例
- C++ vector max_size()用法及代碼示例
- C++ vector shrink_to_fit()用法及代碼示例
- C++ vector capacity()用法及代碼示例
- C++ vector data()用法及代碼示例
- C++ vector insert()用法及代碼示例
- C++ vector rbegin()、rend()用法及代碼示例
- C++ set::emplace()用法及代碼示例
- C++ map emplace()用法及代碼示例
- C++ queue::emplace()用法及代碼示例
- C++ stack emplace()用法及代碼示例
注:本文由純淨天空篩選整理自Twinkl Bajaj大神的英文原創作品 vector emplace() function in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。