2
#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!

4

3 回答 3

4

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 the uint64_t for GetRawData on demand, and return that as a value rather than a reference.

于 2011-04-03T22:30:04.837 回答
3

If you are returning modified data (rather than something directly stored in the container), then you cannot return a reference.

于 2011-04-03T22:30:37.770 回答
1

Here, check out std::pair. In a map, the pair is a mapping of the key to the value:

std::pair<KeyType,ValueType>

So you can access the value by:

ValueType value = pairPtr->second;
// or
ValueType value = pair.second;

Returning references to a value to modify later is simple, here's an example:

const size_t arSize = 8;
pair<int,int> arrr[arSize];

int& value = arrr[0].second;

value = 9;

int returnedValue = arrr[0].second;//you'll notice this equals 9
于 2011-04-03T22:31:22.020 回答