//IDE是vs2013.
vector矢量是c++里一种容器。
assign分配新的内容到容器里,取代旧的内容。
assign用法有两种。
void assign (InputIterator first, InputIterator last);
void assign (size_type n, const value_type& val);
#include "stdafx.h"
#include<iostream>
#include<vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> first;
vector<int> second;
int a[5] = { 1,2, 3, 4, 5};
first.assign(a, a + 5); //assign(InputIterator first, InputIterator last);
second.assign(3, 1);//assign (size_type n, const value_type& val)
for (auto p : first)
{
cout << p << ' ';
}
cout << endl;
for (auto p :second)
{
cout << p << ' ';
}
cout << endl;
system("pause");
return 0;
}
结果:
myvector.assign(6,7);//赋值
myvector.push_back(6);//在末尾添加元素
myvector.pop_back();//移除最后一个元素
myvector.size();//返回vector中的元素个数
<pre name="code" class="cpp">#include <iostream>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> v;
vector<int>::iterator it;
int ar[5] = { 1, 2, 3, 4, 5 };
v.assign(ar,ar+5);//赋值
//myvector.assign(6,7);//或者赋值6个7
v.push_back(6);//在末尾添加元素
v.pop_back();//移除最后一个元素
cout << v.size()<<endl;//返回vector中的元素个数
for (it =v.begin(); it < v.end(); it++)
{
std::cout << *it<<' ';
}
cout<<endl;
system("pause");
return 0;
}
运行结果:
=============
v.at(i);//访问vector中的i个元素
v.front();//访问vector第一个元素
v.back();//访问vector最后一个元素
v.insert(const_iterator position,const value_type& val);
//insert(位置,值)在vector某位置插入一个元素
v.insert(const_iterator position, size_type n, const value_type& val);
//insert(位置,数量n,值)在vector某个位置插入n个元素
v.insert (const_iterator position, 迭代器首地址InputIterator first, 迭代器尾InputIterator last);
//insert(位置,迭代器首地址,迭代器尾)
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> v;
vector<int>::iterator it;
int ar[3] = { 1, 2, 3 };
it = v.begin();
it=v.insert(it, 5);// insert(位置,值)
it=v.insert(it, 1, 4);//insert(位置,数量n,值)
it=v.insert(it,ar,ar+3 );//insert(位置,迭代器首地址,迭代器尾)
cout <<"front:"<< v.front()<<endl;
cout << "back:" << v.back() << endl;
for (auto p : v)
{
cout << p << ' ';
}
cout << endl;
system("pause");
return 0;
}
==================
遍历vector的方法
<pre name="code" class="cpp">#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> v;
vector<int>::iterator it;
int ar[5] = { 1, 2, 3, 4, 5 };
int i=0;
it=v.begin();
it=v.insert(it,ar,ar+5);
for (auto p : v)//第一种
{
cout << p << ' ';
}
cout << endl;
for (i = 0; i < v.size(); i++)//第二种
{
cout << v.at(i) << ' ';
//cout << v[i] << ' ';
}
cout << endl;
system("pause");
return 0;
}