learner
learner

Reputation: 1155

C++ Multimap insert function

I am using multimap to store values. I just want to check while inserting in multimap, if the value is success or failure.

I am trying to use the following code

if (MultiMap.insert(TypeDefMap::value_type(Id, ans)))
  return 1;
else
  return 0;

But this is giving error that scalar types expected.

I think I am missing something silly here. I tried typecasting to int and bool but did not worked.

Any suggestions?

Upvotes: 0

Views: 2712

Answers (4)

snoofkin
snoofkin

Reputation: 8895

according to the docs (of multimap insert method)

In the versions returning a value, this is an iterator pointing to the newly inserted element in the multimap.

you should check if that iterator != end() means success, otherwise, failure.

Upvotes: 2

Jan Hudec
Jan Hudec

Reputation: 76276

The only two things that can fail in std::mutlimap::insert are:

  • Allocation fails, but that throws std::bad_alloc exception.
  • The comparator for key throws an exception, but that exception would be propagated.

(plus some undefined behaviours like calling it on uninitialized instance/bad pointer/..., but that will probably give you a segmentation fault anyway). Since neither returns anything, there is no point in checking whether it succeeded.

Upvotes: 1

Mayank
Mayank

Reputation: 5728

Try using

if(MultiMap.insert(TypeDefMap::value_type(Id, ans)) == MultiMap.end())
    return FAILURE
else
    return SUCCESS

Any returns from the map/set/multimap/multiset, if is iterator, if invalid it should be equal to end().

Upvotes: 0

DanS
DanS

Reputation: 1797

multimap::insert returns an iterator that points to the newly inserted element.

Upvotes: 0

Related Questions