卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章76385本站已运行4321

C++ 自身函数应用举例

c++++ 自身函数示例:字符串操作:std::string::find 函数查找子串。数值转换:std::stoi 和 std::stof 函数分别将字符串转换为整数和浮点数。容器操作:std::vector::push_back 函数添加元素,std::sort 函数对元素排序。输入/输出:std::cin 和 std::cout 分别从标准输入读取和输出数据。时间操作:std::time 函数获取当前时间戳,std::localtime 函数将其转换为本地时间。

C++ 自身函数应用举例

C++ 自身函数应用举例

C++ 提供了丰富的自身函数,用于处理各种数据类型和操作,本文以几个实战案例展示其应用。

1. 字符串操作

立即学习“C++免费学习笔记(深入)”;

string::find 函数用于查找字符串中特定子串的位置,例如:

#include <string>

int main() {
  std::string myString = "Hello, world!";
  size_t pos = myString.find("world");
  if (pos != std::string::npos) {
    std::cout << "Found "world" at position " << pos << std::endl;
  }
  return 0;
}

2. 数值转换

std::stoi 函数将字符串转换为整数,std::stof 函数将字符串转换为浮点数,例如:

#include <iostream>
#include <string>

int main() {
  std::string myString = "123.45";
  int myInt = std::stoi(myString);
  float myFloat = std::stof(myString);
  std::cout << "myInt: " << myInt << std::endl;
  std::cout << "myFloat: " << myFloat << std::endl;
  return 0;
}

3. 容器操作

std::vector::push_back 函数将元素追加到向量末尾,std::sort 函数对容器中的元素进行排序,例如:

#include <iostream>
#include <vector>

int main() {
  std::vector<int> myVector;
  myVector.push_back(1);
  myVector.push_back(3);
  myVector.push_back(2);
  std::sort(myVector.begin(), myVector.end());
  for (int element : myVector) {
    std::cout << element << " ";
  }
  std::cout << std::endl;
  return 0;
}

4. 输入/输出

std::cin 函数从标准输入读取数据,std::cout 函数输出数据到标准输出,例如:

#include <iostream>

int main() {
  int number;
  std::cout << "Enter a number: ";
  std::cin >> number;
  std::cout << "You entered: " << number << std::endl;
  return 0;
}

5. 时间操作

std::time 函数返回当前时间自纪元以来经过的秒数,std::localtime 函数将其转换为本地时间,例如:

#include <ctime>
#include <iostream>

int main() {
  std::time_t currentTime = std::time(nullptr);
  std::tm *localTime = std::localtime(&currentTime);
  std::cout << "Current time: ";
  std::cout << localTime->tm_hour << ":" << localTime->tm_min << ":" << localTime->tm_sec << std::endl;
  return 0;
}
卓越飞翔博客
上一篇: C++ lambda 表达式与闭包在泛型编程中的应用
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏