如何返回对自定义容器中数据的对引用?
#include <cstdint>
#include <utility>
class SimpleMap {
public:
typedef std::pair<const uint32_t, const uint32_t> value_type;
static const int SIZE = 8;
uint64_t data_[SIZE];
SimpleMap() { data_ = {0}; }
// Returning a reference to the contained data.
uint64_t const& GetRawData(size_t index) {
return data_[index];
}
// Would like to return a pair reference to modified data, but how?
// The following wont work: returning reference to temporary
value_type const& GetData(size_t index) {
return value_type(data_[index] >> 32, data_[index] & 0xffffffff);
}
};
map
等容器具有返回对对的引用的迭代器。但这到底是如何运作的呢?如果我向容器写入迭代器,我需要返回对值的引用。但如果这些值是成对的,我该怎么做呢?如果我需要在创建该对时稍微修改数据,如上例所示,该怎么办?
我希望我的问题不会太混乱。请帮忙!
#include <cstdint>
#include <utility>
class SimpleMap {
public:
typedef std::pair<const uint32_t, const uint32_t> value_type;
static const int SIZE = 8;
uint64_t data_[SIZE];
SimpleMap() { data_ = {0}; }
// Returning a reference to the contained data.
uint64_t const& GetRawData(size_t index) {
return data_[index];
}
// Would like to return a pair reference to modified data, but how?
// The following wont work: returning reference to temporary
value_type const& GetData(size_t index) {
return value_type(data_[index] >> 32, data_[index] & 0xffffffff);
}
};
Containers such as map
has iterators that returns a reference to a pair. But how does that even work? If I am writing an iterator to a container, I need to return references to values. But how do I do that if the values are in pairs? And what if I need to slightly modify the data in creating that pair, as in the example above?
I hope my question isn't too confused. Please help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您没有存储对,因此无法返回对已存储对的引用。改为按值返回。
如果您的数组是
value_type data_[SIZE];
您当然可以返回对这些对的引用 - 那么您需要为GetRawData
构造uint64_t
code> 按需,并将 that 作为值而不是引用返回。You're not storing pairs so you cannot return a reference to your stored pair. Return by value instead.
If your array was
value_type data_[SIZE];
you could of course return references to these pairs - then you'd need to construct theuint64_t
forGetRawData
on demand, and return that as a value rather than a reference.如果您返回修改后的数据(而不是直接存储在容器中的数据),则无法返回引用。
If you are returning modified data (rather than something directly stored in the container), then you cannot return a reference.
在这里,查看 std::pair。在映射中,该对是键到值的映射:
因此您可以通过以下方式访问值:
返回对值的引用以供稍后修改很简单,下面是一个示例:
Here, check out std::pair. In a map, the pair is a mapping of the key to the value:
So you can access the value by:
Returning references to a value to modify later is simple, here's an example: