2013-08-22 32 views
0

假设我有类型的变量以下两个表达式等价:是否涉及地图

std::map<int,std::vector<std::string>> m; 

现在声明A是:

m[2].push_back("SomeString"); 

和声明B是:

std::vector<std::string> t = m[2]; 
    m[2]=t.push_back("SomeString"); 

我想知道B是否等于A.

我问这个的原因是因为在这个link上它指出STL对象进行复制。然而,对我来说,声明A似乎会返回一个参考。有关这里发生的事情的任何建议?

+7

你的例子甚至不会编译。 –

+2

s/pushback/push_back? – doctorlove

+6

即使您忽略明显的拼写错误,这也没有多大意义 – nijansen

回答

2

operator[]std::map< class Key, class Value用于获取对应于特定键(实际上,它返回一个引用,但w/e)的值。在你的情况,你会使用这样的:

码片1

std::map<std::string,std::vector<std::string>> m; 
<...> 
std::string the_key_you_need("this is the key"); 
std::vector<std::string> value = m[the_key_you_need]; 
value.push_back(<...>) 

这是不一样的:

码片2

std::map<std::string,std::vector<std::string>> m; 
<...> 
m[the_key_you_need].push_back(<...>); 

因为在第一个中,您正在制作一个副本m[the_key_you_need]命名为value,并将新字符串复制到副本,这意味着它不会在m中结束。第二个是正确的做法。

另外,m[<something>] = value.push_back(<something_else>)将不起作用,因为vector::push_back()返回void。如果你想要做这种方式,你将需要:

码片3

std::map<std::string,std::vector<std::string>> m; 
<...> 
std::string the_key_you_need("this is the key"); 
std::vector<std::string> value = m[the_key_you_need]; 
value.push_back(<...>) 
m[the_key_you_need] = value;//here you are putting the copy back into the map 

在这种情况下,代码段2和3确实是相当的(但这段代码2更好,因为它不会创建不必要的副本)。

+0

说明它返回一个参考解释了很多。我问的原因是,我读到STL与副本一起工作,它总是返回一个副本,并使传递的对象的副本http://stackoverflow.com/questions/14074289/does-passing-stl-containers-make-a -复制。也许我误解了答案 – Rajeshwar

+0

@Raje,我已经编辑了一些答案,以进一步澄清它。你可以检查map的运算符[]'的确是返回一个引用[here](http://en.cppreference.com/w/cpp/container/map/operator_at) – SingerOfTheFall

+0

所以问题是在这种情况下它返回的是复制或参考? – Rajeshwar