Click here to Skip to main content
15,916,835 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am struggling to create a logic to my void method using c++ standard libraries. Basically the code must do the following and currently the code has no implementation yet and stuck.

What I have tried:

C++
<pre>#include <map>
template<typename K, typename V>
class interval_map {
	friend void IntervalMapTest();
	V m_valBegin;
	std::map<K,V> m_map;
public:
	// constructor associates whole range of K with val
	interval_map(V const& val)
	: m_valBegin(val)
	{}

	// Assign value val to interval [keyBegin, keyEnd).
	// Overwrite previous values in this interval.
	// Conforming to the C++ Standard Library conventions, the interval
	// includes keyBegin, but excludes keyEnd.
	// If !( keyBegin < keyEnd ), this designates an empty interval,
	// and assign must do nothing.


void assign( K const& keyBegin, K const& keyEnd, V const& val ) {


}

// look-up of the value associated with key
	V const& operator[]( K const& key ) const {
		auto it=m_map.upper_bound(key);
		if(it==m_map.begin()) {
			return m_valBegin;
		} else {
			return (--it)->second;
		}
	}
};
Posted
Updated 6-Sep-22 5:19am

1 solution

I think you can use an iterator to do this.
C++
void assign( K const& keyBegin, K const& keyEnd, V const& val )
{
    for( auto it = m_map.find( keyBegin ); * it != keyEnd; ++it )
    {
        * it = val;
    }
}
I think that will get you close. I'm not sure because I haven't tried it with a compiler.
 
Share this answer
 
Comments
Gcobani Mkontwana 6-Sep-22 18:30pm    
@Rick York thanks so much, now left with second iteration. Do you mind help need to look for // look-up of the value associated with key.
Rick York 6-Sep-22 18:33pm    
I already showed you - find : https://cplusplus.com/reference/map/map/find/

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900