野百合也有春天

导航

std::vector的一些使用注意事项

  • 使用at()函数而不是operator[]:理由是at()可以抛出invalid vector[T] subscript异常,而operator[]不会做范围检查。因此,at()函数更加安全。
  • 使用vector的assign函数复制一个vector:
include "stdafx.h"
#include <vector>
#include <iostream>

int main( )
{
	using namespace std;
	vector<int> v1, v2, v3;
	vector<int>::iterator iter;

	v1.push_back(10);
	v1.push_back(20);
	v1.push_back(30);
	v1.push_back(40);
	v1.push_back(50);

	cout << "v1 = " ;
	for (iter = v1.begin(); iter != v1.end(); iter++)
		cout << *iter << " ";
	cout << endl;

	v2.assign(v1.begin(), v1.end());
	cout << "v2 = ";
	for (iter = v2.begin(); iter != v2.end(); iter++)
		cout << *iter << " ";
	cout << endl;

	v3.assign(7, 4) ;
	cout << "v3 = ";
	for (iter = v3.begin(); iter != v3.end(); iter++)
		cout << *iter << " ";
	cout << endl;
}

posted on 2010-09-05 20:36  flydream  阅读(2025)  评论(0编辑  收藏  举报