C++ stl::map中运算符[]的奇怪行为
我正在解决一个程序,以防止重复的地图上的值,我写了以下程序C++ stl::map中运算符[]的奇怪行为,c++,c++11,C++,C++11,我正在解决一个程序,以防止重复的地图上的值,我写了以下程序 /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.cpp */ #i
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
*/
#include <map>
#include <limits>
#include<iostream>
using namespace std;
template<typename K, typename V>
class interval_map {
std::map<K,V> m_map;
public:
// constructor associates whole range of K with val by inserting (K_min, val)
// into the map
interval_map( V const& val) {
m_map.insert(m_map.end(),std::make_pair(std::numeric_limits<K>::lowest(),val));
}
void assign( K const& keyBegin, K const& keyEnd, V const& val ) {
if (!(keyBegin < keyEnd)) {
return;
}
else {
if (m_map.rbegin() != m_map.rend()) {
//get the previous key value
auto prev_value = m_map.rbegin()->second;
//compare with current value
if (prev_value == val) {
cout << "duplicate";
//duplicate entry values are restricted, do nothing
}
else {
for (auto i = keyBegin; i<keyEnd; i++) {
cout << i << endl;
m_map[i] = val;
}
}
}
}
}
// look-up of the value associated with key
V const& operator[]( K const& key ) const {
return ( --m_map.upper_bound(key) )->second;
}
};
int main(int argc, char** argv) {
interval_map<unsigned int,char> test('m');
test.assign(2,4,'k');
test.assign(4,7, 'k');
cout << test[5];
return 0;
}
法院
我做错什么了吗
也许吧。这取决于你打算做什么
运算符[]使用的上界查找键大于操作数的元素。您的映射不包含任何大于5†的键,因此该操作返回结束迭代器
然后,运算符[]将迭代器递减,在end iterator的情况下,迭代器将导致最后一个元素的迭代器。映射中的最后一个元素是键值对3,k,因此返回k
†因为正如您所解释的,test.assign4,7,‘k’调用不起任何作用。5在您之前分配的间隔4-7中。那么你期望得到什么呢?顺便说一句,这看起来像是一项个人任务,可能是面试的一部分。继续这样做似乎并不完全合乎道德。但是4-7 interval与赋值方法调用之前的值相同,因此不会赋值。对不起,我不知道你的意思。如果您将2-4作为前面的参考,则4-7不会与之相交。根据你自己的解释,2,4是半开的。I.e.4不包括在内。你期望它做什么?这是一个打字错误,我的意思是问我有没有做错什么,我不明白的是它给地图分配了键5,但是它返回的值是k,但是我没有给它赋值5@manman事实证明,您确实为键5分配了一个值。但是有一个if循环,用于检查该值是否等于上一个assign调用创建的最后一个键的值,可能它没有这样做it@manman我懂了。你应该在问题中更详细地解释你的程序做了什么。太好了,很抱歉,因为我是新来的,所以不能给出upvote分数,上面说upvote需要15分。谢谢,这是我被卡住的地方。所以m_地图[5]在调用之前不存在。