您的位置:首页 > 编程语言 > C语言/C++

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

2015-05-08 10:39 519 查看
在编写代码时发现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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: