Reputation: 40947
With a vector defined as std::vector<std::string>
,
Wondering why the following is valid:
if ( vecMetaData[0] != "Some string" )
{
...
But not this:
switch ( vecMetaData[1] )
{
...
Visual studio complains :
error C2450: switch expression of type 'std::basic_string<_Elem,_Traits,_Ax>' is illegal
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits<char>,
1> _Ax=std::allocator<char>
1> ]
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
Upvotes: 4
Views: 1183
Reputation: 1650
If you just want to check each thing in the vector, you could use the for_each
standard library function. Or if you want to act on a subset of possible values, use find_if
to get iterators for the matching items and then use a loop or for_each
to act on them.
Upvotes: 1
Reputation:
neither of those are probably what you want anyhow... since I assume you want to use the std::string::compare function to do a string comparison
Upvotes: 1
Reputation: 179779
The easiest alternative BTW is a std::map<std::string, boost::function> StringSwitch;
This lets you say StringSwitch["Some string"](arguments...)
Upvotes: 1
Reputation: 17705
switch() needs an integral type (like int, char, ...)
string is not an integral type, neither does string have an implicit conversion to an integral type, so it can't be used in a switch statement
Upvotes: 15
Reputation: 506847
It is valid because the first will call the operator!= of std::string, which will accept a const char* as an argument. That, however, doesn't mean that std::string also has an operator some_integral_type() that will return a integral expression which switch needs.
Using operators in C++ does not necassary invoke the builtin meaning. Your code, for example, doesn't compare pointer values. It might invoke a user defined (in this case, the one of std::string) operator function.
Upvotes: 3