STL vector小结

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

用静态数组初始化vector

一维情况:

int vv[2] = { 12,43 };

std::vector v(&vv[0], &vv[0]+2);

Or, for the case of assignment to an existing vector:

int vv[2] = { 12,43 };

v.assign(&vv[0], &vv[0]+2);

// the iterator constructor can also be used to construct from arrays: int myints[] = {16,2,77,29};

vector fifth (myints, myints + sizeof(myints) / sizeof(int) );

二维情况:

int arr[4][8] =

{

{1, 2, 3, 4, 5, 6, 7, 8},

{1, 2, 3, 4, 9, 10, 11, 12},

{1, 2, 5, 6, 9, 10, 13, 14},

{1, 3, 5, 7, 9, 11, 13, 15},

};

std::vector > vec(4, std::vector(8));

for (int i = 0; i < 4; ++i)

{

vec[i].assign(arr[i], arr[i] + 8);

}

例子:

float arrOfPos[][2] = { {501,10}, {501,128} };

int nPosNum = sizeof(arrOfPos) / sizeof(float) / 2;

vector< vector > vecOfPos(nPosNum, vector(2, 0));

for (int i = 0; i < nPosNum; i++)

vecOfPos[i].assign(arrOfPos[i], arrOfPos[i]+2);

float arrOfNeg[][2] = { {255, 10}, {501, 255}, {10, 501} };

int nNegNum = sizeof(arrOfNeg) / sizeof(float) / 2;

vector< vector > vecOfNeg(nNegNum, vector(2, 0));

for (int i = 0; i < nNegNum; i++)

vecOfNeg[i].assign(arrOfNeg[i], arrOfNeg[i]+2);

删除指定的元素:

for(vector::iterator iter=veci.begin(); iter!=veci.end();注意此处)

{

if( *iter == 3)

iter = veci.erase(iter); // An iterator that designates the first element remaining beyond any elements removed, or a pointer to the // end of the vector if no such element exists//在erase后,it失效,并不是指向vector的下一个元素,it成了一个“野指针”,返回的是指向下一个元素的迭代器

else

iter ++ ;

}

vector中insert()的用法详解

iterator insert( iterator loc, const TYPE &val );

void insert( iterator loc, size_type num, const TYPE &val );

void insert( iterator loc, input_iterator start, input_iterator end );

insert() 函数有以下三种用法:

在指定位置loc前插入值为val的元素,返回指向这个元素的迭代器,

在指定位置loc前插入num个值为val的元素

在指定位置loc前插入区间[start, end)的所有元素 .

注意点:insert是插入到指定position的前面,而不是后部。

The vector is extended by inserting new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted.

This causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.

在一个vector尾部append另一组数据:

#include

#include

using namespace std;

int main() {

vector nums;

for(int i = 1; i <= 10; ++i)

nums.push_back(i);

vector appends;

for(int i = -5; i <= -1; ++i)

appends.push_back(i);

nums.insert(nums.end(), appends.begin(), appends.end()) ;

for(int i = 0; i < nums.size(); ++i)

cout<

cout<

return 0;

}

结果:Compiling the source code....

$g++ -std=c++11 main.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1 Executing the program....$demo 1 2 3 4 5 6 7 8 9 10 -5 -4 -3 -2 -1

在vector中循环插入长度相等的vector:

vector subnums;

for(int i = 1; i <= 10; ++i)

subnums.push_back(i);

vector nums(40, 0);

相关文档
最新文档