C ++ switch usage

Source: Internet
Author: User

Let's take a look at the definition of switch in C ++:

Values Based on Integer expressions can be selected from multiple parts of the Code.

switch ( expression )   case constant-expression : statement   [default  : statement]

Expression in SwitchIt must be an integer, character, or enumeration value.

That is to say, I cannot use it like this:

string s="123";switch(s){     case "1":{             break;     }     case "23":{            break;     }     、、、}

This tangle (C #, JS can judge the string). In order to be able to use the switch statement, we can only match the string with the value one by one, but this is also very troublesome. For example:

int getIndex(std::string *s,std::string str){int index;for(int i=0;i<s->length();i++){if(s[i]==str){index=i;break;}}return index;}int main(){string str="12",ss;string s[10]={"123","12"};int i=getIndex(s,str);switch(i){case 1:{ss+="100";break;}default:{ss+="default";break;}}cout<<ss<<endl;}

This method is fine. You need to add a branch each time and add a string to the array, and then add a case for processing. Similar methods include:

int main(){string str="12",ss;int i;if(str=="12")i=1;if(str=="123")i=2;switch(i){case 1:{ss+="100";break;}default:{ss+="default";break;}}cout<<ss<<endl;}

This is the most direct method, but if there are many branches, there will be a lot of if statements. I personally prefer the first one. If you have a good method, please post it for discussion and study!

Author:Kunoy Source:Http://blog.csdn.net/kunoy Statement:The authors write blogs to sum up experience and exchange learning.
If you need to reprint the statement, please keep it as much as possible and provide the original article connection clearly on the article page. Thank you!

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.