473,398 Members | 2,113 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,398 software developers and data experts.

assignment/initialization of container - map

Hi,

I want to define a map:

std::map<string, intmyMap;

e.g., the score of students. Then I can assign the value as follows:
myMap["stud1"] = 90;
myMap["stud2"] = 60;
....

My question now is: can I assign the name of many students in one line?
e.g., for array we have the following way:
int myArray[] = { 1, 3, 4, 5 };

Do we have similar way for map?
std::map<string, intmyMap = { ("stud1", 90), ("stud2", 60) };
// wrong code

Another question: how can I print the score of a given student's name?

void getScore(std::map<string, intmyMap, const std::string& stuName)
{
return myMap.find(stuName)->second();
}

Is this correct? Any better solution?

Thanks in advance!

-X
Jul 18 '06 #1
8 4340
xuatla wrote:
I want to define a map:

std::map<string, intmyMap;

e.g., the score of students. Then I can assign the value as follows:
myMap["stud1"] = 90;
myMap["stud2"] = 60;
...

My question now is: can I assign the name of many students in one line?
e.g., for array we have the following way:
int myArray[] = { 1, 3, 4, 5 };

Do we have similar way for map?
No.
std::map<string, intmyMap = { ("stud1", 90), ("stud2", 60) };
// wrong code

Another question: how can I print the score of a given student's name?

void getScore(std::map<string, intmyMap, const std::string& stuName)
{
return myMap.find(stuName)->second();
}

Is this correct? Any better solution?
First, unless you want to DRASTICALLY inefficient, better to pass the
map by reference instead of by value. Second, you can't return a value
if you declare the function void. Finally, although theoretically
slightly less efficient, more clear in my view is to use operator[] and
dump the separate function altogether:

myMap[stuName]

or if you insist on the separate function, make it:

int getScore(std::map<string, int>& myMap, const std::string& stuName)
{
return myMap[stuName];
}

Best regards,

Tom

Jul 18 '06 #2
xuatla wrote:
Hi,

I want to define a map:

std::map<string, intmyMap;

e.g., the score of students. Then I can assign the value as follows:
myMap["stud1"] = 90;
myMap["stud2"] = 60;
...

My question now is: can I assign the name of many students in one line?
e.g., for array we have the following way:
int myArray[] = { 1, 3, 4, 5 };

Do we have similar way for map?
std::map<string, intmyMap = { ("stud1", 90), ("stud2", 60) };
// wrong co
No, map's not an aggregate.

The best you can do is something like:

struct apair {
const char* s;
int i;
} maptab[] = { { "stud1", 90 }, ....

for(apair* ap = maptab; ap != sizeof maptab/sizeof (apair); ++ap)
myMap[ap->s] = ap->i;
Jul 18 '06 #3
Ron Natalie wrote:
xuatla wrote:
>Hi,

I want to define a map:

std::map<string, intmyMap;

e.g., the score of students. Then I can assign the value as follows:
myMap["stud1"] = 90;
myMap["stud2"] = 60;
...

My question now is: can I assign the name of many students in one
line? e.g., for array we have the following way:
int myArray[] = { 1, 3, 4, 5 };

Do we have similar way for map?
std::map<string, intmyMap = { ("stud1", 90), ("stud2", 60) };
// wrong co
No, map's not an aggregate.

The best you can do is something like:

struct apair {
const char* s;
int i;
} maptab[] = { { "stud1", 90 }, ....

for(apair* ap = maptab; ap != sizeof maptab/sizeof (apair); ++ap)
myMap[ap->s] = ap->i;
Shouldn't this work

std::map<string,intmyMap(maptab, maptab +
sizeof(maptab)/sizeof(*maptab));

? You might find that using [] instead of .insert() is less efficient.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 18 '06 #4
Thomas Tutone <Th***********@yahoo.comwrote:
xuatla wrote:
>Another question: how can I print the score of a given student's name?

void getScore(std::map<string, intmyMap, const std::string& stuName)
{
return myMap.find(stuName)->second();
}

Is this correct? Any better solution?

First, unless you want to DRASTICALLY inefficient, better to pass the
map by reference instead of by value. Second, you can't return a value
if you declare the function void. Finally, although theoretically
slightly less efficient, more clear in my view is to use operator[] and
dump the separate function altogether:

myMap[stuName]

or if you insist on the separate function, make it:

int getScore(std::map<string, int>& myMap, const std::string& stuName)
{
return myMap[stuName];
}
However, if stuName is not already in the map, the myMap[stuName]
version will automatically create an entry for it, and
default-initialize(?, maybe it's zero-initialize) it. Using
myMap.find(), this case can be handled separately if desired.

// untested and uncompiled
int getScore(const std::map<std::string, int>& myMap,
const std::string& stuName)
{
std::map<std::string, int>::const_iterator i = myMap.find(stuName);

if (i != myMap.end()) {
return i->second;
}
else {
return -1;
}
}

I do agree that the myMap[stuName] syntax is easier to read though,
however it cannot be used on a const map (or a reference to a const map)
because of the automatic-entry-creation behavior.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Jul 18 '06 #5

Victor Bazarov wrote:
Ron Natalie wrote:
xuatla wrote:
I want to define a map:

std::map<string, intmyMap;

e.g., the score of students. Then I can assign the value as follows:
myMap["stud1"] = 90;
myMap["stud2"] = 60;
...

My question now is: can I assign the name of many students in one
line? e.g., for array we have the following way:
int myArray[] = { 1, 3, 4, 5 };

Do we have similar way for map?
std::map<string, intmyMap = { ("stud1", 90), ("stud2", 60) };
// wrong co
No, map's not an aggregate.

The best you can do is something like:

struct apair {
const char* s;
int i;
} maptab[] = { { "stud1", 90 }, ....

for(apair* ap = maptab; ap != sizeof maptab/sizeof (apair); ++ap)
myMap[ap->s] = ap->i;

Shouldn't this work

std::map<string,intmyMap(maptab, maptab +
sizeof(maptab)/sizeof(*maptab));
I could be wrong about this, but I don't think that would work. The
map<string, intconstructor would be expecting iterators pointing to
pair<string, int>, and would get instead an iterator to struct { const
char*, int }. Unless there's some sort of implicit conversion going on
that I don't understand, your example shouldn't compile. Even if it
were a map<const char*, int>, I think it still wouldn't work, because a
struct { const char*, int } is different from a pair<const char*, int>.

Or maybe I'm wrong.

Best regards,

Tom

Jul 18 '06 #6
Victor Bazarov wrote:
\
Shouldn't this work

std::map<string,intmyMap(maptab, maptab +
sizeof(maptab)/sizeof(*maptab));

? You might find that using [] instead of .insert() is less efficient.
I would have if I had used pairs. However, you can't use aggregate
initializers on pairs so I had to choose between making the insert
nice or the static initializer.

Jul 18 '06 #7
Thomas Tutone wrote:
xuatla wrote:
I want to define a map:

std::map<string, intmyMap;

e.g., the score of students. Then I can assign the value as follows:
myMap["stud1"] = 90;
myMap["stud2"] = 60;
...

My question now is: can I assign the name of many students in one line?
e.g., for array we have the following way:
int myArray[] = { 1, 3, 4, 5 };

Do we have similar way for map?

No.
There are several similar but not identical ways for std::map. See the
other responses in this thread for initializing from an array, and also
consider a helper class that uses method chaining (see the FAQ for more
on that):

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<int,std::stringmsgMap
= MapInitializer<int,std::string>()
.Add( 1, "Msg 1" )
.Add( 2, "Msg 2" )
.Add( 42, "Msg 3" );

Cheers! --M

Jul 18 '06 #8

Thomas Tutone wrote:
xuatla wrote:
I want to define a map:

std::map<string, intmyMap;

e.g., the score of students. Then I can assign the value as follows:
myMap["stud1"] = 90;
myMap["stud2"] = 60;
...

My question now is: can I assign the name of many students in one line?
e.g., for array we have the following way:
int myArray[] = { 1, 3, 4, 5 };

Do we have similar way for map?

No.
std::map<string, intmyMap = { ("stud1", 90), ("stud2", 60) };
// wrong code

Another question: how can I print the score of a given student's name?

void getScore(std::map<string, intmyMap, const std::string& stuName)
{
return myMap.find(stuName)->second();
}

Is this correct? Any better solution?

First, unless you want to DRASTICALLY inefficient, better to pass the
map by reference instead of by value. Second, you can't return a value
if you declare the function void. Finally, although theoretically
slightly less efficient, more clear in my view is to use operator[] and
dump the separate function altogether:

myMap[stuName]

or if you insist on the separate function, make it:

int getScore(std::map<string, int>& myMap, const std::string& stuName)
{
return myMap[stuName];
}
Thanks for your reply. "void" is my typo. I think I was dumb when I
stated my question in above way. I got the answers from the replies
here now. Thanks to all.

- X

btw : an off-topic question: I use thunderbird to read newsgroups.
Today I found that I couldn't read the latest threads in it (the most
recent ones shown was posted at yesterday). Is there anyone else
encountered same questions? Which software do you think is best for
newsgroups reading/posting? Now I am using Google groups to read the
threads here. (I just came back from Mars and this is my first time
using Google groups for newsgroups...)

>
Best regards,

Tom
Jul 18 '06 #9

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

Similar topics

2
by: Grumble | last post by:
Hello all, What, if any, is the difference between string s("toto"); string s = "toto"; In the first case, I am using the constructor: basic_string(const value_type *ptr);
50
by: Charles Stapleton | last post by:
Given the folowing class class Ctest{ public: Ctest( int i, int j) :a(i) { b = j; } private: int a, b; } When creating an object of type Ctest, what advantage is there to setting
2
by: Matthias Kaeppler | last post by:
Hi, say I have an arbitrary class Bar: 1 Bar a; 2 Bar b(a); 3 Bar c = a; In line 3, is the default ctor called for c _first_ and _then_ the assignment operator, or is c never default...
6
by: Neil Zanella | last post by:
Hello, I would like to know whether the following C fragment is legal in standard C and behaves as intended under conforming implementations... union foo { char c; double d; };
7
by: skishorev | last post by:
What is the difference between copy initialization and assignment. How the memory will allocates the objects. Thanks &regards, Sai Kishore
19
by: scroopy | last post by:
Is it impossible in C++ to create an assignment operator for classes with const data? I want to do something like this class MyClass { const int m_iValue; public: MyClass(int...
8
by: heng | last post by:
I define my own assignment operator, but it doesn't work as I imagined. #include<iostream> #include <string> using namespace std; class A{ int x; public: int y;
4
by: Jess | last post by:
Hello, I tried several books to find out the details of object initialization. Unfortunately, I'm still confused by two specific concepts, namely default-initialization and...
3
by: Bram Kuijper | last post by:
Hi all, I am trying to resize a vector of objects (MyObj below), which contain references to other objects (OtherObj, see below). However, apparently somewhere in the resize operation an...
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?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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,...
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...
0
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,...
0
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...

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.