加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – std :: vector:连续数据和复制/移动

发布时间:2020-12-16 07:53:33 所属栏目:百科 来源:网络整理
导读:我有以下代码的两个问题:1)面孔的元素会连续吗? 2)std :: vector复制或移动Face f插入吗? #include vector int main(){ struct Face {}; std::vectorFace faces; for (int i=0; i10; ++i) { Face f; faces.push_back (f); } return 0;} 解决方法 根据标准
我有以下代码的两个问题:1)面孔的元素会连续吗?
2)std :: vector复制或移动Face f插入吗?
#include <vector>    
int main()
{
    struct Face {};
    std::vector<Face> faces;

    for (int i=0; i<10; ++i)
    {
        Face f;

        faces.push_back (f);
    }

    return 0;
}

解决方法

根据标准§23.3.6.1类模板向量概述[vector.overview]:

The elements of a vector are stored contiguously,meaning that if v is a vector<T,Allocator> where T is some type other than bool,then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().

就现在C11编译器而言,第二个问题push_back会复制你推回的对象.

在C 11之后,这取决于因为push_back有两个重载,一个采用一个左值引用,另一个引用一个rvalue引用.

在你的情况下,它将被复制,因为你将对象作为左值传递.为了确保对象的移动,您可以使用std :: move().

faces.push_back(std::move(f));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读