473,657 Members | 2,851 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

STL MAP, how to restrict

#include <iostream>
#include <map>
#include <string>

using namespace std;
void InitMap( map<string, int>& Map)
{
Map["aa"] = 0;
Map["bb"] = 0;
}

int main() {

map<string, intMyMap;

InitMap( MyMap);

MyMap["aa"] = 10;// Questione 1

MyMap["cc"] = 20;// Question 2

map<string, int>::const_ite rator iter;
for (iter=MyMap.beg in(); iter != MyMap.end(); iter++) {
cout << iter->first << " " << iter->second << endl;
}

return 0;

}
Question 1:

How do I create my own map, which would allow me to check during

MyMap["aa"] = 10;

that values for "aa" can be from 0 to 5, so the above assignment
would print error message.
Question 2:

How do I prevent my map to be only 2 elements, "aa" and "bb", so
creation of new element "cc" would not be allowed.

Thanks,
-haro
(I tried and failed, I googled and failed, so I came here.
Please excuse if this is very simple or discribed somewhere)
Nov 15 '06 #1
5 1731
Haro Panosyan wrote:
#include <iostream>
#include <map>
#include <string>

using namespace std;
void InitMap( map<string, int>& Map)
{
Map["aa"] = 0;
Map["bb"] = 0;
}

int main() {

map<string, intMyMap;

InitMap( MyMap);

MyMap["aa"] = 10;// Questione 1

MyMap["cc"] = 20;// Question 2

map<string, int>::const_ite rator iter;
for (iter=MyMap.beg in(); iter != MyMap.end(); iter++) {
cout << iter->first << " " << iter->second << endl;
}

return 0;

}
Question 1:

How do I create my own map, which would allow me to check during

MyMap["aa"] = 10;

that values for "aa" can be from 0 to 5, so the above assignment
would print error message.
Question 2:

How do I prevent my map to be only 2 elements, "aa" and "bb", so
creation of new element "cc" would not be allowed.

Thanks,
-haro
(I tried and failed, I googled and failed, so I came here.
Please excuse if this is very simple or discribed somewhere)
What you seem to need is a "wrapper" for 'std::map'. Since your
own 'map' is not an extension of 'std::map' (you want to impose
limitations on 'std::map' contents, which means your map is not
a std::map in the pure OO sense, see LSP), you should consider
private inheritance and re-implementation of the interface with
pre- and post-conditions verified in your implementations .

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 15 '06 #2

Haro Panosyan wrote:
>
How do I create my own map, which would allow me to check during

MyMap["aa"] = 10;

that values for "aa" can be from 0 to 5, so the above assignment
would print error message.
Question 2:

How do I prevent my map to be only 2 elements, "aa" and "bb", so
creation of new element "cc" would not be allowed.
It sounds to me like a map is totally inappropriate for your needs.
You should consider a different container or even no container at all.
You're using none of map's features.

Nov 15 '06 #3
Haro Panosyan wrote:
#include <iostream>
#include <map>
#include <string>

using namespace std;
void InitMap( map<string, int>& Map)
{
Map["aa"] = 0;
Map["bb"] = 0;
}

int main() {

map<string, intMyMap;

InitMap( MyMap);

MyMap["aa"] = 10;// Questione 1

MyMap["cc"] = 20;// Question 2

map<string, int>::const_ite rator iter;
for (iter=MyMap.beg in(); iter != MyMap.end(); iter++) {
cout << iter->first << " " << iter->second << endl;
}

return 0;

}
Question 1:

How do I create my own map, which would allow me to check during

MyMap["aa"] = 10;

that values for "aa" can be from 0 to 5, so the above assignment
would print error message.
Create a class that does range checking and automatically converts to
and from int, e.g. (untested code):

#include <map>
#include <string>
#include <exception>

template<typena me T, T lower, T upper>
class RangeCheckedVal
{
T val_;

static T Validate( const T& val )
{
if( val < lower || val upper )
{
throw std::range_erro r( "Value out of range" );
}
return val;
}

public:
RangeCheckedVal ( const T& val = lower )
: val_( Validate(val) )
{}

operator T() const { return val_; }
};

int main()
{
std::map<std::s tring, RangeCheckedVal <int,0,5 myMap;
myMap[ "aa" ] = 5; // ok
myMap[ "bb" ] = 10; // throws an exception
}
Question 2:

How do I prevent my map to be only 2 elements, "aa" and "bb", so
creation of new element "cc" would not be allowed.
Make the map const. To do this, you'd need to initialize the class on
declaration somehow, e.g.:

template<class K, class V>
class MapInitializer
{
typedef std::map<K,VMap ;
Map m_;
public:
operator Map() const { return m_; }

MapInitializer& Add( const K& k, const V& v )
{
m_[k] = v;
return *this;
}
};

const std::map<std::s tring,intmyMap
= MapInitializer< std::string, int>()
.Add( "aa", 9 )
.Add( "bb", 42 );

Of course, if the map is const, the [] operator won't work (outside the
initializer) since it inserts a key/value pair if one doesn't exist,
but std::map::find( ) is safer anyway.

Cheers! --M

Nov 15 '06 #4
Please find my comments bellow inserted.

mlimber wrote:
Haro Panosyan wrote:
>>#include <iostream>
#include <map>
#include <string>

using namespace std;
void InitMap( map<string, int>& Map)
{
Map["aa"] = 0;
Map["bb"] = 0;
}

int main() {

map<string, intMyMap;

InitMap( MyMap);

MyMap["aa"] = 10;// Questione 1

MyMap["cc"] = 20;// Question 2

map<string, int>::const_ite rator iter;
for (iter=MyMap.beg in(); iter != MyMap.end(); iter++) {
cout << iter->first << " " << iter->second << endl;
}

return 0;

}
Question 1:

How do I create my own map, which would allow me to check during

MyMap["aa"] = 10;

that values for "aa" can be from 0 to 5, so the above assignment
would print error message.


Create a class that does range checking and automatically converts to
and from int, e.g. (untested code):

#include <map>
#include <string>
#include <exception>

template<typena me T, T lower, T upper>
class RangeCheckedVal
{
T val_;

static T Validate( const T& val )
{
if( val < lower || val upper )
{
throw std::range_erro r( "Value out of range" );
}
return val;
}

public:
RangeCheckedVal ( const T& val = lower )
: val_( Validate(val) )
{}

operator T() const { return val_; }
};

int main()
{
std::map<std::s tring, RangeCheckedVal <int,0,5 myMap;
myMap[ "aa" ] = 5; // ok
myMap[ "bb" ] = 10; // throws an exception
}

Thank,
This is nice, but I think this way both "aa" and "bb" would have
same range. What I wanted, is somehow to overwrite assignment, and
check if "aa" then range is 0 to 5, if "bb" then range is 3 to 9
for example.
>>Question 2:

How do I prevent my map to be only 2 elements, "aa" and "bb", so
creation of new element "cc" would not be allowed.


Make the map const. To do this, you'd need to initialize the class on
declaration somehow, e.g.:

template<class K, class V>
class MapInitializer
{
typedef std::map<K,VMap ;
Map m_;
public:
operator Map() const { return m_; }

MapInitializer& Add( const K& k, const V& v )
{
m_[k] = v;
return *this;
}
};

const std::map<std::s tring,intmyMap
= MapInitializer< std::string, int>()
.Add( "aa", 9 )
.Add( "bb", 42 );

Of course, if the map is const, the [] operator won't work (outside the
initializer) since it inserts a key/value pair if one doesn't exist,
but std::map::find( ) is safer anyway.

Cheers! --M
I will need more time to exercise this.
Nov 15 '06 #5
Haro Panosyan wrote:
>Question 1:

How do I create my own map, which would allow me to check during

MyMap["aa"] = 10;

that values for "aa" can be from 0 to 5, so the above assignment
would print error message.

Create a class that does range checking and automatically converts to
and from int, e.g. (untested code):

#include <map>
#include <string>
#include <exception>

template<typena me T, T lower, T upper>
class RangeCheckedVal
{
T val_;

static T Validate( const T& val )
{
if( val < lower || val upper )
{
throw std::range_erro r( "Value out of range" );
}
return val;
}

public:
RangeCheckedVal ( const T& val = lower )
: val_( Validate(val) )
{}

operator T() const { return val_; }
};

int main()
{
std::map<std::s tring, RangeCheckedVal <int,0,5 myMap;
myMap[ "aa" ] = 5; // ok
myMap[ "bb" ] = 10; // throws an exception
}

Thank,
This is nice, but I think this way both "aa" and "bb" would have
same range. What I wanted, is somehow to overwrite assignment, and
check if "aa" then range is 0 to 5, if "bb" then range is 3 to 9
for example.
Then you'll probably want to implement your own class that encapsulates
a map (or some other data structure).

Cheers! --M

Nov 15 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

28
6407
by: gc | last post by:
Hi, What is the purpose of the restrict keyword? gc
4
2186
by: Vijay Kumar R Zanvar | last post by:
Greetings, Are the following inferences of mine correct? 1. #include <string.h> char *strcpy(char * restrict s1, const char * restrict s2); a. s1 != s2 b. That means,
7
2666
by: tweak | last post by:
Can someone give me a short example as how to best use this keyword in your code? This is my understanding: by definition restrict sounds like it is suppose to restrict access to memory location(s) pointed to, so that only one declared pointer can store that address and access the data in those memory blocks, where I the data in those location(s) can be changed. Is that a correct understanding?
1
2500
by: ccdrbrg | last post by:
I'm having trouble understanding restrict. Can someone provide a layman's explanation. Chad
2
2406
by: pemo | last post by:
In Harbison and Steele's book, they say that using 'restrict' allows functions like memcpy() to be prototyped like this: void * memcpy(void * restrict s1, const void * restrict s2, size_t n); But this seems a mite dangerous to me ... a restricted pointer ... is *assumed* to be the only to access an object. So, mightn't using such a prototype subtly imply that the compiler will *actively check* that s1 and s2 do not point to the same
12
2492
by: Me | last post by:
I'm trying to wrap my head around the wording but from what I think the standard says: 1. it's impossible to swap a restrict pointer with another pointer, i.e. int a = 1, b = 2; int * restrict ap = &a; int * restrict bp = &b;
21
6500
by: Niu Xiao | last post by:
I see a lot of use in function declarations, such as size_t fread(void* restrict ptr, size_t size, size_t nobj, FILE* restrict fp); but what does the keyword 'restrict' mean? there is no definition found in K&R 2nd.
2
3256
by: venkat | last post by:
Hi, i came across restrict qualifier while looking the code. I haven't able to understand what does this do?. Can some one help me how does this makes the things restrict to an specified objects. It will be good, if explained with example. Appriciate your help in this regard. Thanks,
0
2982
by: copx | last post by:
Restrict keyword questions How far does the guarantee that an object is not accessed through another pointer go? I mean, all examples I have seen are simple stuff like: int f (int *restrict x, int *restrict y) { *x = 0; *y = 1; return *x;
23
4819
by: raashid bhatt | last post by:
what is restrict keyword used for? eg int *restrict p;
0
8385
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8821
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8723
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8502
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7316
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6162
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4300
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1941
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.