前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >蓝桥ROS机器人之现代C++学习笔记4.1 线性容器

蓝桥ROS机器人之现代C++学习笔记4.1 线性容器

作者头像
zhangrelay
发布2022-04-29 19:44:25
1980
发布2022-04-29 19:44:25
举报
文章被收录于专栏:机器人课程与技术

学习的程序如下:

代码语言:javascript
复制
#include <iostream>
#include <array>
#include <vector>

void foo(int *p, int len) {
    for (int i = 0; i != len; ++i) {
        std::cout << p[i] << std::endl;
    }
}

int main() {
    std::vector<int> v;
    std::cout << "size:" << v.size() << std::endl;         // output 0
    std::cout << "capacity:" << v.capacity() << std::endl; // output 0

    // As you can see, the storage of std::vector is automatically managed and 
    // automatically expanded as needed.
    // But if there is not enough space, you need to redistribute more memory, 
    // and reallocating memory is usually a performance-intensive operation.
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    std::cout << "size:" << v.size() << std::endl;         // output 3
    std::cout << "capacity:" << v.capacity() << std::endl; // output 4

    // The auto-expansion logic here is very similar to Golang's slice.
    v.push_back(4);
    v.push_back(5);
    std::cout << "size:" << v.size() << std::endl;         // output 5
    std::cout << "capacity:" << v.capacity() << std::endl; // output 8

    // As can be seen below, although the container empties the element, 
    // the memory of the emptied element is not returned.
    v.clear();                                             
    std::cout << "size:" << v.size() << std::endl;         // output 0
    std::cout << "capacity:" << v.capacity() << std::endl; // output 8

    // Additional memory can be returned to the system via the shrink_to_fit() call
    v.shrink_to_fit();
    std::cout << "size:" << v.size() << std::endl;         // output 0
    std::cout << "capacity:" << v.capacity() << std::endl; // output 0


    std::array<int, 4> arr= {1,4,3,2};
    
    //int len = 4;
    //std::array<int, len> arr = {1,2,3,4}; // illegal, size of array must be constexpr
    
    // C style parameter passing
    // foo(arr, arr.size());           // illegal, cannot convert implicitly
    foo(&arr[0], arr.size());
    foo(arr.data(), arr.size());

    // more usage
    std::sort(arr.begin(), arr.end());
    for(auto &i : arr)
        std::cout << i << std::endl;
    
    return 0;
}

看了C++版本还是要更新支持到c++20才行。 

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-04-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档