C++ STL iota 和 atoi 用法

一:功能

iota 是给定一个初始元素,然后依次对序列中每个元素进行递增++操作,详见代码一;

atoi 是将字符串转换成整数;atol, atoll 将字符串转换成长整型数 long,long long。

二:用法

cpp 复制代码
#include <iostream>
#include <vector>
#include <numeric>

int main() {
    std::vector<int> data(9, 0);
    for (auto v : data)
        std::cout << v << " ";
    std::cout << "\n";

    //对序列中元素进行累加, -4是初始值 
    std::iota(data.begin(), data.end(), -4); 
    for (auto v : data)
        std::cout << v << " ";
    std::cout << "\n";
    //4 -3 -2 -1 0 1 2 3 4
}
cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    printf("%i\n", atoi(" -123junk"));
    printf("%i\n", atoi(" +321dust"));
    printf("%i\n", atoi("0"));
    printf("%i\n", atoi("0042")); // treated as a decimal number with leading zeros
    printf("%i\n", atoi("0x2A")); // only leading zero is converted discarding "x2A"
    printf("%i\n", atoi("junk")); // no conversion can be performed
    printf("%i\n", atoi("2147483648")); // UB: out of range of int
}
相关推荐
感哥6 小时前
C++ 面向对象
c++
沐怡旸7 小时前
【底层机制】std::shared_ptr解决的痛点?是什么?如何实现?如何正确用?
c++·面试
感哥14 小时前
C++ STL 常用算法
c++
saltymilk1 天前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥1 天前
C++ lambda 匿名函数
c++
沐怡旸1 天前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥1 天前
C++ 内存管理
c++
博笙困了2 天前
AcWing学习——双指针算法
c++·算法
感哥2 天前
C++ 指针和引用
c++
感哥2 天前
C++ 多态
c++