【C++】 <atoi><stoi><to_string> 转换类函数 《解析 + 例题》

3 篇文章 0 订阅

1. stoi()

stoi()的参数是const string

作用

将字符串转换为整数
解析 传入的字符串(string)将其内容解析为指定基数的整数,该基数作为 int 值返回。

返回值

成功时,函数将转换后的整数作为 int 值返回。
Ps:
如果 str 中的第一个非空白字符序列不是有效整数,或者由于 str 为空或仅包含空白字符而不存在此类序列,则不执行转换并返回零。

2. atoi()

atoi() 的参数是 const char*,因此对于一个字符串str我们必须调用 c_str() 把这个string转换成const char类型

作用

  1. 解析 C 字符串 string,将其内容解释为整数,该整数作为 int 类型的值返回。
  2. 该函数首先根据需要丢弃尽可能多的空白字符(如在 isspace 中),直到找到第一个非空白字符。然后,从这个字符开始,采用可选的初始加号或减号,后跟尽可能多的 base-10 数字,并将它们解析为数值。

返回值

  1. 成功时,函数将转换后的整数作为 int 值返回。 如果转换后的值超出 int 可表示值的范围,则会导致未定义的行为。如果可能,请参阅
    strtol 以获得更强大的跨平台替代方案。
  2. On success, the function returns the converted integral number as an int value.
    If the converted value would be out of the range of representable values by an int, it causes undefined behavior.

3. to_string

作用

将字符串转换为整数
解析 传入的字符串(string)将其内容解析为指定基数的整数,该基数作为 int值返回。

返回值

配套练习(to_string + stoi)

1. 点击跳转

class Solution 
{
public:
    bool isSameAfterReversals(int num) 
    {
        int t = num;
        string ret = to_string(num);
        while(ret.size() > 1 && (*(ret.end() -1)) == 0  )
            ret.pop_back();
            cout <<ret;
        if(num >= 0)
        {
            reverse(ret.begin(),ret.end());
        }
        else reverse(ret.begin() + 1,ret.end());

        reverse(ret.begin(),ret.end());
        cout<<ret;
        return t == stoi(ret);
    }
};

2. 点击跳转->习题二

class Solution {
public:
    vector<int> sortJumbled(vector<int>& mapping, vector<int>& nums) 
    {
        map<int,vector<int>> mp;
        for(int i = 0 ; i < nums.size();  i++)
        {
            string t = to_string(nums[i]);//将三位数转化为string
            for(auto &x : t)//映射
            {
                x = mapping[x - '0'] + '0';
            }
            mp[stoi(t)].push_back(nums[i]);//建立映射关系

        }

        vector<int> ret;
        for(auto [x,y] : mp)
            for(auto& val : y)      ret.push_back(val);

        return ret;
    }
};
评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值