可以避免这个副本吗? [英] Can this copy be avoided?
本文介绍了可以避免这个副本吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设你有一个类型A,它有一些与我们想要避免的复制相关的成本。
我想要一个集合在哪里A形成钥匙的一部分,比如...
std :: map< std :: pair< A,int>,std :: string> myMap;
现在我想看看这样......
void SomeMethod( const A& a, int b)
{
iterator it = myMap.find(std :: make_pair(a,b));
}
... make_pair(...)复制A,因为地图的密钥类型是< pre lang =c ++> std :: pair< A,int>
not
std :: pair< const A&,int>
有人可以建议一种避免A副本的方法吗?
解决方案
//不是std :: pair< const A&,int>
为什么不呢?
它也可以是std :: pair< const A *,int>
或std :: pair< std :: auto_ptr< A>&,int>
:)
通常你不想使用大对象密钥。
您也可以在某处保留std :: pair< a,>
通过参考SomeMethod
传递它,以避免在循环中特别构造额外的构造。
你使用整个A
订购对象?如果没有,那么可能更好的设计是拥有更简单的密钥和更完整的价值。
通常你的密钥应该是简单的,小的对象和价值会得到所有的信息。类似的东西:
struct PairAndString
{
第一个;
int 秒;
std :: string third;
};
// 只有在密钥中进行排序和比较所需的字段。其他所有东西都移到了价值部分。
std :: map< a_key,> MYMAP;
Suppose you have a type A which has some cost associated with copying it that we''d like to avoid.
I want to have a collection where A forms part of the key, say...
std::map< std::pair<A, int>, std::string> myMap;
Now I want to do a look up like this...
void SomeMethod(const A& a, int b)
{
iterator it = myMap.find(std::make_pair(a, b));
}
...make_pair(...) copies the A because the map''s key type is
std::pair<A, int>
not
std::pair<const A&, int>
Can anyone suggest a way to avoid the copy of A?
解决方案
// notstd::pair<const A&, int>
Why not ?
It could be alsostd::pair<const A*, int>
orstd::pair<std::auto_ptr<A>&, int>
:)
Typically you don''t want to use large object for a key.
You might also be able to keep astd::pair<a,>
somewhere and pass it by reference toSomeMethod
to avoid extra construction particulary in a loop.
Are you using the wholeA
object for ordering ? If not, then maybe a better design would be to have a simpler key and a more complete value.
Generally your key should be simple and a small object and the value would have all the information. Something similar to this:
struct PairAndString { A first; int second; std::string third; }; // Only fields necessary for sorting and comparison in key. Everything else moved to the value part. std::map<a_key,> myMap;
这篇关于可以避免这个副本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文