21xrx.com
2025-03-26 21:02:49 Wednesday
文章检索 我的文章 写文章
【分享】C++有趣的代码轻松复制
2023-06-21 19:10:24 深夜i     11     0
C++ 代码 有趣 复制 分享

C++是一种常用的编程语言,但许多人会发现自己在编写代码时会遇到一些挑战。在这篇文章中,我们将向您介绍一些有趣的代码,帮助您更轻松地复制代码。

以下是一些有趣的C++代码:

1.使用向量将元素两两交换:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
 vector<int> vec10;
 for(int i=0;i<vec.size()-1;i+=2)
  swap(vec[i],vec[i+1]); //使用swap函数将两个元素交换
 for(auto i:vec) //打印结果
  cout<<i<<" ";
 return 0;
}

2.反转字符串:

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
 string str{"Hello World!"};
 reverse(str.begin(), str.end()); //使用reverse函数反转字符串
 cout<<str; //打印反转后的字符串
 return 0;
}

3.使用cctype库检查字符串是否为数字:

#include<iostream>
#include<string>
#include<cctype>
using namespace std;
int main()
{
 string str{"1234"};
 bool isNumber=true; //设定初始值为true
 for(auto c:str)
 {
  if(!isdigit(c)) //如果字符不是数字
  
   isNumber=false; //将isNumber设置为false
   break; //退出循环
  
 }
 if(isNumber)
  cout<<"是数字"<<endl; //输出结果
 else
  cout<<"不是数字"<<endl; //输出结果
 return 0;
}

希望这些代码可以帮助你在使用C++时更轻松地复制代码。

  
  

评论区

请求出错了