我将构造函数和两个函数添加到我之前的链接问题 C++ iterate through a template Map 的类中在这一点上我需要帮助:
- 你认为这个构造函数的作用是什么?
- 在 map 的开头添加一个值?
- 在 main 中初始化后,我看到在各自的键中只有一个地址作为值。怎么了?
运算符 [] 应该获取特定键的值。但是我不能使用它来获取输出中的 map 元素。有什么提示吗?
template<class K, class V>
class template_map{
public:
template_map( V const& val) {
m_map.insert(my_map.begin(),std::make_pair(std::numeric_limits<K>::min(),val));
};
typedef typename std::map<K,V> TMap;
TMap my_map;
typedef typename TMap::const_iterator const_iterator;
const_iterator begin() const { return my_map.begin(); }
const_iterator end() const { return my_map.end(); }
V const& operator[]( K const& key ) const {
return ( --my_map.upper_bound(key) )->second;
}
...
};
int main()
{
interval_map<int,int> Map1 (10);
//Show the elements of the map?
}
还要考虑它应该是一个向 map 插入值的函数。
最佳答案
What do you reckon this constructor does? Adding one value at the beginning of map?
它初始化 map 使得map[x] == v
对于任何 x
.该映射将间隔与值相关联,在内部存储以每个间隔的开始为键的法线映射;它被初始化,以便键类型的整个范围映射到初始值。
I see though in the respective key only an address as value after initializing in main. What is wrong? The operator [] is supposed to get the values for a specific key. However I cannot use it so as to get the elements of the map in the output. Any hint?
我不知道你在那里问什么。例如,如果您尝试 cout << Map1[42] << '\n';
, 那么你的程序应该输出 10
,因为这是分配给整个整数范围的初始值。
Consider also that it should be a function that inserts values to the map.
由于内部 map 是公开的,你可以用
向 map 添加一个新的间隔Map1.my_map.insert(std::make_pair(interval_start, value));
my_map
可能更礼貌私有(private),并提供 insert()
功能来做到这一点。您可以还添加 operator[]
的非常量重载插入一个新范围并返回对其值的引用,类似于
V & operator[](K const & key) {
V const & old_value = (--my_map.upper_bound(key))->second;
return *my_map.insert(std::make_pair(key, old_value)).first;
}
尽管这可能不是一个好主意,因为您必须小心不要在只想读取值时意外插入许多范围。
My problem is how to iterate through the map to get all its elements and print them in main. It shows me an address with a value of the object initialization.
请记住, map 上的迭代器指的是键/值对(类型为 std::pair<K,V>
),您应该能够像这样在 map 上迭代:
for (auto it = Map1.begin(); it != Map1.end(); ++it) {
std::cout << it->first << " maps to " << it->second << '\n';
}
(在 C++03 中,您需要编写 template_map<int,int>::const_iterator
而不是 auto
)。
关于C++模板类映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8414433/