开发者

How do I assign a std::pair that have one of it's component typed const?

I'm trying to code an associative container compatible with std::map. To do so, I have to create an insert method that accept a new item in the form of an std::pair with the first component of a const type. For example : std::pair<const int, int> p.

The problem I have is that such an object can't be assigned to another. So in the inner code of my MapCompatibleContainer, I can't cop开发者_StackOverflowy the new pair to the private variable (a std::vector).

How can I work around this?

Thanks


As you say, you cannot assign to a const object.

The standard containers solve this by allocating raw memory and construct the object in place. Copy construction still works.

Also, the associative containers store each element in a separate memory block, so that they don't have to be copied later.


There is a helper function in the <utility> section of the standard library which holds a std::make_pair function. If you use that you can take your pair and do the following:

foo.insert( std::make_pair( bar.first, bar.second ) );

where I'm assuming the "foo" is your own implementation of an object that is compatible to "map."

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜