You can simply do courses.find(mystring) != courses.end()
.
Value assigned by double default constructor in c++
문제
I have this variable:
std::map<std::string, double> courses;
And I'd like to print it if it has a value assigned for some key. So my keys are strings, so I want something like:
std::cin >> mystring;
if (!(courses[mystring] == x)) std::cout << courses[mystring] << std::endl;
but I don't know what to make x. Any ideas?
해결책
다른 팁
Use the following approach
auto it = courses.find( mystring );
if ( it != courses.end() ) std::cout << it->second << std::endl;
An alternative is to use member function count
. It is even simpler than using method find because there is no need to define the iterator.
if ( courses.count( mystring ) ) std::cout << courses[mystring] << std::endl;
Or even it would be better to write
if ( courses.count( mystring ) != 0 ) std::cout << courses[mystring] << std::endl;
You can use map::find
to check if there is an item in the map corresponding to a key.
std::map<std::string, double>::iterator iter = courses.find(mystring);
if ( iter != courses.end() )
{
std::cout << iter->second << std::endl;
}
Using find
and using the returned iterator makes more sense to me since you have to search for the item only once.
Using something like:
if( courses.count( mystring ) )
{
cout << courses[mystring] << endl;
}
has the advantage that the code is simpler. However, it potentially comes at a cost. You may have to search for the item twice.
if( courses.count( mystring ) )
{
cout << courses[mystring] << endl;
}
Don't optimize prematurely, just write what's simplest and most clear.
I.e. using count
, [1]as above.
In this case an optimization using more convoluted and verbose code with find
would be extremely [2]marginal, since reuse of an iterator can't in general compare to the time involved in i/o, so I advice against that.
1) You can add a comparision with 0 or e.g. a
!!
conversion to bool
, if the old C convention of using a number directly as a boolean looks cryptic or weird.2) One might think that using
count
would force a redundant second search for the item, but a map implementation is free to store the last found iterator value as hint for the next search, reducing that to O(1) in this case. E.g. see the complexity of std::map::emplace_hint
. That alone classifies this optimization consideration as premature, and additionally there is the order-of-magnitude difference between i/o and searching in a small collection, not to mention the complexity (additional variable) and verbosity of the iterator based code.