473,386 Members | 1,773 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Initializing a map...


Is there a way in C++ to initialize an STL map in one statement (the way
arrays can be initialized in C)?

For example, instead of using:

map<type1,type2mymap;
mymap[key1] = value1;
mymap[key2] = value2;
I would like to use something like:

// wrong syntax!
map<type1,type2mymap = { (key1, value1), (key2, value2) };


Feb 20 '08 #1
5 17444
barcaroller wrote:
Is there a way in C++ to initialize an STL map in one statement (the way
arrays can be initialized in C)?

For example, instead of using:

map<type1,type2mymap;
mymap[key1] = value1;
mymap[key2] = value2;
I would like to use something like:

// wrong syntax!
map<type1,type2mymap = { (key1, value1), (key2, value2) };
There's no special syntax for maps. You do have a few options, though.
One is to initialize an array with the nicer syntax, then initialize
the map from the array.

typedef std::map<type1, type2map_type;
typedef map_type::value_type pair_type;

template<typename T, std::size_t z>
std::size_t size(T const (&a)[z]) {
return z;
}

int main() {
pair_type initializers[] =
{ pair_type(key1, value1), pair_type(key2, value2) };
map_type m(initializers, initializers + size(initializers));
}

Another option is to create the map within a function, then return it by
value.

map_type create_map() {
map_type result;
result.insert(pair_type(key1, value1));
result.insert(pair_type(key2, value2));
return result;
}

int main() {
map_type map = create_map();
}

A third option is to let the map start out empty, then use a function to
populate it.

void populate(map_type& m) {
m.insert(pair_type(key1, value1));
m.insert(pair_type(key2, value2));
}

int main() {
map_type m;
populate(m);
}
Feb 21 '08 #2
Your messages always have the text as an attachment instead of in the body
of the message. Just thought you might want to know.

--
Jim Langston
ta*******@rocketmail.com
"Sam" <sa*@email-scan.comwrote in message
news:co*****************************@commodore.ema il-scan.com...
Feb 21 '08 #3
On Feb 21, 4:22 am, "Alf P. Steinbach" <al...@start.nowrote:
* Jim Langston:
Your messages always have the text as an attachment instead
of in the body of the message. Just thought you might want
to know.
Only for Outlook Express users... ;-)
Or Google groups.
It seems Outlook Express is the only commonly used newsreader
that doesn't handle digitally signed messages correctly.
For what definition of "correctly"? According to the RFC,
attachments are not allowed in news, so arguably, "correctly"
would mean not displaying or propagating the message:-).
(Realistically, of course: the first rule is always "be liberal
in what you accept, and conservative in what you send". No good
newsreader would ever append an attachment, but all good
newsreaders would accept it. And allowing at least a digital
signature does seem a reasonable extension to me.)

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Feb 21 '08 #4
Sam
Jeff Schwab writes:
>>
#include <iostream>
#include <ostream>

int main()
{
std::map<int, intm(map_initializer(3,4)(5,6)(7,8));
...
> return 0;
}

That's a neat idea. It could probably be made a little more efficient
by replacing the calls to map::operator[] with calls to map::find and
operator[] takes only one argument. You can use a std::pair, but it'll make
this even more ugly.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (GNU/Linux)

iD8DBQBHvWo7x9p3GYHlUOIRAnzkAJ9rd3VYOlnl6mk9f6Nk2m Vwbrt4/QCbBVn+
wvGArnNFpaAb6SHW9LJnAJU=
=2p1k
-----END PGP SIGNATURE-----

Feb 21 '08 #5
James Kanze wrote:
On Feb 21, 1:22 am, Jeff Schwab <j...@schwabcenter.comwrote:
>barcaroller wrote:
>>Is there a way in C++ to initialize an STL map in one
statement (the way arrays can be initialized in C)?
>>For example, instead of using:
>> map<type1,type2mymap;
mymap[key1] = value1;
mymap[key2] = value2;
>>I would like to use something like:
>> // wrong syntax!
map<type1,type2mymap = { (key1, value1), (key2, value2) };
>There's no special syntax for maps.

I think there will be in the next version of the standard. (I
know that there was a proposal for extended initializers, but
I'm not sure what the current status of the proposal was.)
The proposal:
http://www.open-std.org/jtc1/sc22/wg...2007/n2215.pdf

I didn't know about that. Very neat. I'm not thrilled with g++ warning
me about:

std::tr1::array<int, 42= { 0 }; // g++ wants { { 0 } }

It would bother me less if there were consistent syntax for primitive
and UD types.

>You do have a few options, though.
> One is to initialize an array with the nicer syntax, then initialize
the map from the array.

This is the only way to create a const map.
That's a very good point, and is the reason my "not really
initialization" solutions are inferior.
> int main() {
pair_type initializers[] =
{ pair_type(key1, value1), pair_type(key2, value2) };
map_type m(initializers, initializers + size(initializers));
}

I often find it worthwhile to define a special structure for
this, something along the lines of:

typedef std::map< std::string, double Map ;
struct MapInit
{
char const* key ;
double value ;
operator Map::value_type() const
{
return Map::value_type( std::string( key ), value ) ;
}
} ;
Is the key stored as a char const* so that construction of the
initializers does not require any run-time overhead? Does MapInit count
as a POD type, and is there benefit to using POD initializers?
Feb 21 '08 #6

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

Similar topics

50
by: Dan Perl | last post by:
There is something with initializing mutable class attributes that I am struggling with. I'll use an example to explain: class Father: attr1=None # this is OK attr2= # this is wrong...
14
by: Avi Uziel | last post by:
Hi All, I'm writing a Windows DLL which contain some utility classes. One of my classes is Singleton, therefore contain some static members. I'm using VC6 and linking to the DLL statically. ...
2
by: Wynne | last post by:
Can anyone here tell me about initializing high-values? I want to create a generic stored procedure that will perform the following Select * from ? where ? between parm1 and parm2 no...
1
by: Mike Davison | last post by:
I've made a program that fetches data from an ODBC data source. Everything works fine when the table contains only a few rows. The problem is that when there are many rows (6000, in this case),...
8
by: SM | last post by:
I've always wonder if there is diference when declaring and initializing a varible inside/outside a loop. What's a better practice? Declaring and initializing variables inside a loop routine,...
38
by: junky_fellow | last post by:
Guys, I was just looking at some code where to initialize an integer with all F's following statement is used; unsigned int i = -1; I want to know if this is the right way of doing the...
10
by: Jason Doucette | last post by:
Situation: I have a simple struct that, say, holds a color (R, G, and B). I created my own constructors to ease its creation. As a result, I lose the default constructor. I dislike this, but...
13
by: WaterWalk | last post by:
Hello. When I consult the ISO C++ standard, I notice that in paragraph 3.6.2.1, the standard states: "Objects with static storage duration shall be zero-initialized before any other...
6
by: Jai Prabhu | last post by:
Hi All, Consider the following piece of code: void func (void) { static unsigned char arr = "\x00\xAA\xBB"; fprintf (stderr, "0x%x\n", arr); fprintf (stderr, "0x%x\n", arr);
9
by: Mark2012 | last post by:
Hello, I am new to programming with python. I am using the tutorial, "Byte of Python" and am on p. 82. I have come across something very unusual by accident and I was wondering if anybody here could...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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...

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.