2011-04-03 20 views
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); 
    } 
}; 

諸如map之類的容器具有迭代器,該迭代器返回對一對的引用。但是,這甚至如何工作?如果我正在寫容器的迭代器,我需要返回對值的引用。但是,如果這些值是成對的,我該怎麼做呢?如果我需要稍微修改創建該對中的數據,如上例所示?如何將一個對引用返回到自定義容器中的數據?

我希望我的問題不要太困惑。請幫忙!

回答

4

您不存儲對,因此您無法返回對存儲對的引用。按價值返回。

如果陣列是value_type data_[SIZE];你當然可以返回引用給這些成對的 - 那麼你就需要構建uint64_tGetRawData需求,並返回作爲一種價值,而不是一個參考。

+0

啊,這麼明顯。現在一切都說得通了。我錯誤地假設了一些我見過的容器以更復雜的方式存儲元素,並使用一些魔法來返回對引用。但是,當然,他們只是實際存儲配對。 – porgarmingduod 2011-04-03 22:37:27

3

如果您要返回修改後的數據(而不是直接存儲在容器中的東西),則不能返回引用。

1

在這裏,檢查出std::pair。在地圖中,對是關鍵值的映射:

std::pair<KeyType,ValueType> 

所以,你可以通過訪問該值:

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

返回引用的值再進行修改很簡單,這裏的一個例子:

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 
相關問題