溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C++中tostring函數的擴展應用

發布時間:2024-09-08 10:21:39 來源:億速云 閱讀:144 作者:小樊 欄目:編程語言

std::to_string 是 C++11 標準庫中的一個函數,它可以將數字類型(如 int、float、double 等)轉換為字符串。然而,std::to_string 只能處理基本的數字類型,對于更復雜的數據結構,我們需要自定義轉換函數。

以下是一些 std::to_string 的擴展應用示例:

  1. 將自定義類型轉換為字符串
#include<iostream>
#include<string>

class Person {
public:
    std::string name;
    int age;

    // 自定義轉換函數
    std::string to_string() const {
        return "Name: " + name + ", Age: " + std::to_string(age);
    }
};

int main() {
    Person person{"Alice", 30};
    std::cout<< person.to_string()<< std::endl;
    return 0;
}
  1. 將容器轉換為字符串
#include<iostream>
#include<vector>
#include<string>

template<typename T>
std::string container_to_string(const std::vector<T>& container) {
    std::string result = "[";
    for (size_t i = 0; i< container.size(); ++i) {
        result += std::to_string(container[i]);
        if (i != container.size() - 1) {
            result += ", ";
        }
    }
    result += "]";
    return result;
}

int main() {
    std::vector<int> numbers{1, 2, 3, 4, 5};
    std::cout<< container_to_string(numbers)<< std::endl;
    return 0;
}
  1. 將時間轉換為字符串
#include<iostream>
#include <ctime>
#include<string>

std::string time_to_string(const std::tm& time) {
    char buffer[20];
    std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &time);
    return std::string(buffer);
}

int main() {
    std::time_t now = std::time(nullptr);
    std::tm* local_time = std::localtime(&now);
    std::cout<< time_to_string(*local_time)<< std::endl;
    return 0;
}

這些示例展示了如何使用 std::to_string 的基本思想來擴展其應用范圍,以適應更復雜的數據類型和場景。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

c++
AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女