emplace
This is a new feature in C++11 to add the element in container(like stack, list, forward list) constructed from arguments.
It has many API, few of them are:
- emplace(itr, value); //Add the element at given position, need to pass iterator(position) and value
- emplace_front(value); //Add the element at first position, need to pass value
- emplace_back(value); //Add the element at last position, need to pass value
Example:
std::list<std::string> lst; lst.emplace_front("three"); //Add at first lst.emplace(lst.begin(), "four"); //Add at first, position is first lst.emplace_back("five"); //Add at last
source code with example:
/* Program: Emplace Author: Alpha Master Date: 13 March 2021 */ //Header File #include<iostream> #include<list> void display(const std::list<std::string>& tmpList) { for(auto a: tmpList) { std::cout<<a<<std::endl; } return; } int main() { std::cout<<"Emplace"<<std::endl; std::list<std::string> lst; lst.push_back("one"); lst.push_back("two"); lst.emplace_front("three"); //Add at first lst.emplace(lst.begin(), "four"); //Add at first lst.emplace_back("five"); //Add at last display(lst); return 0; }
Output:
Emplace four three one two five