The problem of comparing STL vectors

With a vector defined as std::vector<std::string> , consider why the following is true:

 if ( vecMetaData[0] != "Some string" ) { ... 

But not this:

 switch ( vecMetaData[1] ) { ... 

Visual Studio complains:

error C2450: expression expression like 'std :: basic_string <_Elem, _Traits, _Ax>' is illegal 1> with 1> [1> _Elem = char, 1> _Traits = std :: char_traits, 1> _Ax = std :: allocator 1>] 1> A user transformation operator is available that can perform this conversion, or the operator cannot be called

+4
source share
6 answers

switch () requires an integral type (e.g. int, char, ...)

Line

is not an integral type, and the string does not have an implicit conversion to an integral type, so it cannot be used in the switch statement

+14
source

This is true because the first will call the! = Operator from std :: string, which will accept the const char * argument. This, however, does not mean that std :: string also has the operator some_integral_type (), which will return the integral expression that the switch requires.

Using operators in C ++ does not require you to have a built-in value. For example, your code does not compare pointer values. It can call a user-defined operator function (in this case, one of std :: string).

+3
source

You can use the switch only for basic data types (int, char, etc.).

+2
source

The simplest BTW option is std::map<std::string, boost::function> StringSwitch;

This allows you to say StringSwitch["Some string"](arguments...)

+1
source

If you just want to check every thing in a vector, you can use the standard for_each library function. Or, if you want to act on a subset of the possible values, use find_if to get iterators for the corresponding elements, and then use a loop or for_each to act on them.

+1
source

none of them are likely needed, since I assume you want to use the std :: string :: compare function to compare strings

+1
source

All Articles