1.C++条件操作符--(问号?)
随着程序越来与复杂,会在代码中出现越来越多的if语句。有些时候我们只要电脑做一个简单的判断,就要用占据多行的if语句,实在有点吓人,使得程序的可读性受到一定的影响。
条件操作符具体语法为:(条件表达式)?(条件为真时的表达式):(条件为假时的表达式);它的运算优先级比逻辑或还低,是目前为止优先级最低的操作符。
那么条件操作符执行时间与if-else判断语句的执行时间是否有差异,看下列代码:
String AA = "eeeeee";
String BB = "dddddddd";
// time0 为执行条件执行语句所花费的时间
double time0 = static_cast<double>(getTickCount());
cout << ((AA.size() > BB.size()) ? AA : BB) << endl;
time0 = ((double)getTickCount() - time0) / getTickFrequency();
cout << time0 << endl;
cout << "\n\n" << endl;
// time1 为执行if-else所花费的时间
double time1 = static_cast<double>(getTickCount());
if (AA.size() > BB.size())
{
cout << AA << endl;
}
else
{
cout << BB << endl;
}
time1 = ((double)getTickCount() - time1) / getTickFrequency();
cout << time1 << endl;
最终执行效果如下图所示:
2. char与String
在编程中常常需要将int类型转化为string类型,若int AA = 12;String AAS = to_String(AA)即可。
char:char是字符类型,C++基本数据类型(8位)。
string:string是字符串类型,扩展类,可以将其理解为一个容器,用来存储多个char类型。自带length(),begin()等方法。
char*,char[ ],string都可以存放字符串,具体可以参加博客:http://www.cnblogs.com/SnailProgramer/p/4275798.html(整理的比较全)
1)赋值&&替换
char赋值:strcpy(ch1,ch2),其中ch1,ch2都属于char[ ]类型;strncpy(ch1,ch2,3),ch2的前三个数替换到ch1,而ch1中的其他数字不发生变化,其中ch1,ch2属于char[ ]类型。
string赋值:str1 = str2或者str1.assign(str2,1,3)(代表此时str1的值为str2的从第二个元素开始取,总共取三个元素值)。str1.replace(0,1,str2,4,2),意为将str2从下标4开始2个字符替换掉str1中从起始位置开始的1个字符。
2)合并
char合并:strcat(ch1,ch2),其中ch1,ch2都属于char[ ]类型;strncat(ch1,ch2,3),其中ch1和ch2为char[ ]类型,参数3为从起始位置起的字符数,将符合要求的这些字符从ch2复制到ch1。
string合并:str1 = str1 + str2,str1.append(str2, 1, 2);(代表str1加上str2从第二个元素开始的两个字符)。
3)长度
char长度:int length = strlen(ch1),其中ch1属于char[ ]或者char*类型。
string长度:int length = str1.size()或者int length = str1.length()。
3. 寻找vector<int>或vector<double>中的最大值或最小值
如下,寻找DecisionValue中的最大值,将对应的下标保存至DecisionIndex中。(可使用max_element。)
vector<double> DecisionValue;
vector<int> DecisionIndex;
for (size_t i = 0; i < DecisionValue.size(); i++)
{
auto Max_Value = max_element(DecisionValue.begin(), DecisionValue.end());
int locationIndex = Max_Value - DecisionValue.begin();
DecisionIndex.push_back(locationIndex);
DecisionValue[locationIndex] = -1;
}
4. vector类型如果需要初始化容器的数量,用resize即可
vector<int> NumV;
NumV.resize(80); // 这样就将vector进行了初始化
5. 将数组的值赋值为同一个元素
int a[100] = {0}; // 100个元素的值都为0