简体   繁体   English

C ++传递STL容器项作为参考

[英]C++ pass STL container items as reference

I have a map of type std::map<std::string, std::vector<MyClass>> . 我有一个std::map<std::string, std::vector<MyClass>>类型的std::map<std::string, std::vector<MyClass>> The map is filled in this way that I create a vector and put it with a guid as a pair into the map. 地图以这种方式填充,我创建了一个向量,并将guid作为一对放入地图中。 Then I want to call a function, give the just inserted vector to it and let it fill the vector. 然后我想调用一个函数,给它刚刚插入的向量并让它填充向量。 It looks like that: 它看起来像这样:

{
    std::string guid = "aGUID"
    std::vector<MyClass> vec_myClass(0);
    my_map[guid] = vec_myClass;
    std::vector<MyClass>& vec_ref = my_map[guid];

    FillVector(vec_ref);    
}

FillVector(std::vector<MyClass>& vec)  { vec.push_back(...); }

I think the [] operator returns a reference of the item in my_map , which I can give to a function to work with it, but my application crashes at this point. 我认为[]运算符返回my_map项目的my_map ,我可以将它提供给一个函数来处理它,但我的应用程序此时崩溃了。 I am putting the vector first into the map (when it is empty) because I want to avoid copying effort as function FillVector puts lots of items into the vector. 我将向量首先放入地图(当它是空的时)因为我想避免复制工作,因为函数FillVector将大量项目放入向量中。 Where is my mistake? 我的错误在哪里? Might it be wrong to pass a reference by reference to a function? 通过引用函数传递引用可能是错误的吗? Or is there a clearly better solution to this? 或者有一个明显更好的解决方案吗? I prefer references over pointers here. 我更喜欢这里引用指针。 Thx, and all the best. 谢谢,一切顺利。

All that code simplifies to: 所有代码都简化为:

{
    std::string guid = "aGUID"
    FillVector(my_map[guid]);    
}

Btw. 顺便说一句。 I think your problem does not appear to be here, but in code you don't show us... 我认为你的问题似乎不在这里,但在代码中你没有告诉我们......

std::map operator would create value for the key internally if it does not exist. 如果密钥不存在,std :: map运算符将在内部为密钥创建值。 see this link . 看到这个链接 passing the reference to function is ok, the problem seem to be somewhere else in your code. 将引用传递给函数是好的,问题似乎是在代码中的其他地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM