C++ vector的访问(resize,pu_back与下标访问的区别)

来源:互联网 发布:滴滴企业版软件下载 编辑:程序博客网 时间:2024/05/23 10:30
在编写代码时发现vector的一个现象
(1)
  std::vector<std::string> str_vector;
  str_vector.resize(3);
  str_vector.push_back("name_1");
  str_vector.push_back("name_2");


 然后进行访问逐一打印发现:
 for (std::vector<std::string>::iterator iter = str_vector.begin(); iter != str_vector.end(); ++iter)
   {
     std::cout<<*iter<<", ";
  }
  其值为:"","","","name_1","name_2",
  此时发现resize是开辟了三个string空间,而后push_back是接着前面开辟的空间而往里push.

(2)
  std::vector<std::string> str_vector;
  str_vector.push_back("name_1");
  str_vector.push_back("name_2");

    其值为:"name_1","name_2",

(3)
  std::vector<std::string> str_vector;
  str_vector[0] = "name_1";  //wrong,错误,vector大小未知,且没有元素.
  // 下标只能用于获取已存在的元素

总结:
 (1)  若想对vector进行下面访问,则必须空间已开辟,可以用:
          std::vector<std::string> str_vector;
          str_vector.resize(3);
          str_vector[0] = "name_1";  
          str_vector[1] = "name_2";  
          str_vector[2] = "name_3";  
       也可用:
  std::vector<std::string> str_vector;
    str_vector.push_back("name_1");
    str_vector.push_back("name_2");
  for(int i=0; i< str_vector.size(); i++)
         {
           std::cout<<str_vector[i]<<std::endl;
         }

 (2) 请注意resize()与push_back的同时使用,其空间是resize的空间+push_back的空间,否则达不到预设目标.



欢迎大家批评,指正,交流!

联系方式:

emai:  tongzhuodenilove@163.com
0 0
原创粉丝点击