GODF's blog

By GODF, history, 4 weeks ago, In English,

Hi. I have following problem. Yesterday I tried to solve this problem The same code with emplace_back does not pass the system test. However the same code with push_back passes the system test. So my question is: What is happening here ? Link to the submission with push_back Link to the submission with emplace_back

 
 
 
 
  • Vote: I like it
  • +29
  • Vote: I do not like it

»
4 weeks ago, # |
  Vote: I like it +35 Vote: I do not like it

push_back creates a copy of the object you want to insert before pushing it to the vector and hence it modifies the type accordingly (in this case to long double) whereas emplace_back just moves the argument to the vector and hence the element remain of the same type and here you can check that atan2 is a built-in function that returns a double and not a long double.

So your problem was with precision and not with the use of push_back and emplace_back.

  • »
    »
    4 weeks ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Thank you! Now i got it. When I cast it to long double it gets accepted.

  • »
    »
    4 weeks ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    That doesn't make sense to me, emplace_back just calls some constructor with the arguments, and there the double would be cast to long double in my understanding.

»
4 weeks ago, # |
  Vote: I like it +6 Vote: I do not like it

Unless you need to worry about things like exception handling, don't use emplace_back. It isn't faster.

»
4 weeks ago, # |
  Vote: I like it +14 Vote: I do not like it

emplace_back can also be used to append objects with fewer characters. For example for a vector<pair<int,int>> you can do: vec.emplace_back(a,b)

  • »
    »
    4 weeks ago, # ^ |
      Vote: I like it +13 Vote: I do not like it

    Similarly, you can go with vec.push_back({a, b}).

  • »
    »
    4 weeks ago, # ^ |
      Vote: I like it +53 Vote: I do not like it

    But vec.emplace_back(a, b) has one more character than vec.push_back({a, b})... :D

    • »
      »
      »
      4 weeks ago, # ^ |
        Vote: I like it +6 Vote: I do not like it

      Ok, you got me there. Just to pretend Im not completely wrong, you can also use emplace_back when you use structs or classes. For example for a struct for points named pt and for vector vec you can use vec.emplace_back(x,y) in comparision to vec.push_back(pt(x,y)). (Plus you can do #define eb emplace_back)