在c ++中将元素添加到空向量中:为什么push.back有效,[]不起作用 [英] add an element to an empty vector in c++: why push.back works and [] not

查看:61
本文介绍了在c ++中将元素添加到空向量中:为什么push.back有效,[]不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几年前,我在大学里接受了c ++入门课程.但是,我主要使用R或Matlab等功能语言.现在,我再次开始学习c ++.我正在阅读有关向量的内容,并在以下代码中运行:

Some years ago I had an introductory course to c++ at my university. However, I mainly used functional languages such as R or Matlab. Now I started again to learn c++. I was reading about vectors and run in the following:

    #include <iostream>
    #include <string>
    #include <algorithm>
    #include <vector>

    int main()
    {      
      std::vector<int> test1;
  std::vector<int> test2(2);

  // works perfectly as expected:
  test2[0] = 1;
  test2[1] = 2;
  // this would give an error
  //test1[0] = 1;

  //instead I have to write
  test1.push_back(1);

      return 0;
    } 

如果我对test1使用默认初始化,为什么必须使用puch_back?使用[]运算符并自动插入元素不是更聪明"吗?为什么在c ++中禁止这样做?

If I use default initialization for test1, why do I have to use puch_back? Wouldn't it be "smarter" to use the [] operator and automatically insert the element? Why is this forbidden in c++?

推荐答案

std :: vector operator [] 具有与之相同的语义.用于纯数组.也就是说,它使您可以访问具有特定索引的 existing 元素.空向量没有现有元素,因此您必须将它们添加到其中. push_back 是实现此目的的一种方法.它的作用是在向量的后面附加一个新元素,将其元素数增加1.

std::vector's operator[] is designed to have the same semantics as it does for plain arrays. That is, it gives you access to an existing element with a certain index. An empty vector has no existing elements, so you have to add them in. push_back is one way of doing that. It has the effect of appending a new element to the back of a vector, increasing its number of elements by 1.

这篇关于在c ++中将元素添加到空向量中:为什么push.back有效,[]不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆