confusion about the parameter of "emplace"

this is the declaration of "emplace":
template <class... Args>
iterator emplace (const_iterator position, Args&&... args);

so i wonder if i can pass multiple parameters to emplace and write the code below.

1
2
3
4
5
6
7
//necessary headfiles are included
int main(){
    vector<int> coll({1,4,5,6});
    coll.emplace(coll.begin(),2,3,5);
    print(coll);//a function that cout each elements of "coll"
    return 0;
}

It finally gets wrong.But when i change the parameters likes that:
 
coll.emplace(coll.begin(),2);

It works. I wonder what is the meaning of"...args" at the declaraion?If it is a variadic template,why can't i pass mutiple numbers to "coll"?What's the wrong with my code?
Apperciate it if you can do me a favour.
Last edited on
Hi a3700235. You have a weird name. Lol.

See if these links can help you a little.

https://www.cplusplus.com/reference/vector/vector/emplace/
https://en.cppreference.com/w/cpp/container/vector/emplace


Forgotten Coder
Last edited on
Like the reference says it emplaces elements before interator:

1
2
3
4
5
6
int main(){
    vector<int> coll({1,4,5,6});
    coll.emplace(coll.begin() + 2 ,2,3,5);
    print(coll);//a function that cout each elements of "coll"
    return 0;
}
It emplaces one element, not elements.

The "...args" is a parameter pack. See https://en.cppreference.com/w/cpp/language/parameter_pack

In your case the element has type int, so the parameter pack needs exactly one int to initialize the element with.


With insert() and push_back() you need value_type value.
The emplace() and emplace_back() pass ...args to constructor of value_type.
1
2
3
4
5
6
7
8
9
10
11
class Person {
  // code
public:
  Person( const std::string&, int );
};

int main() {
  std::vector<Person> group;
  group.insert( group.begin(), Person( "Jack", 16 ) );
  group.emplace( group.begin(), "Jill", 17 );
}
Topic archived. No new replies allowed.