C++ string and vector(二)

      标准库类型vector表示对象的集合,其中全部的对象的类型都相同。集合中的每一个对象的每一个对象都有一个与之对应的索引,索引用于访问对象。由于vector“容纳”其余对象,因此也常称做容器(container)
ios

    C++语言既有类模板(class template),也有函数模板,其中vector是一个类模板
c++

以vector为例,提供的额外的信息是vector内所存放对象的类型:算法

记得加上头文件:数组

#include <vector>


vector<int> ivec;                //ivec保存int类型的对象curl

vector<string> file;            //file保存string类型的对象函数

       vector<vector<string>> file;  //该向量的元素是vector对象url

使用vector有两种不一样的形式,即所谓的数组习惯和 STL习惯。spa

1、数组习惯用法指针

1. 定义一个已知长度的 vector :code

vector< int > ivec( 10 );  //相似数组定义int ia[ 10 ];

能够经过ivec[索引号] 来访问元素

使用 if ( ivec.empty() ) 判断是不是空,ivec.size()判断元素个数。

 

2. vector的元素被初始化为与其类型相关的缺省值:算术和指针类型的缺省值是 0,对于class 类型,缺省值可经过调用这类的缺省构造函数得到,咱们还能够为每一个元素提供一个显式的初始值来完成初始化,例如  
vector< int > ivec( 10, -1 ); 
定义了 ivec 它包含十个int型的元素 每一个元素都被初始化为-1 

对于内置数组 咱们能够显式地把数组的元素初始化为一组常量值,例如 : 
int ia[ 6 ] = { -2, -1, 0, 1, 2, 1024 };


咱们不能用一样的方法显式地初始化 vector ,可是能够将 vector 初始化为一个已有数组的所有或一部分,只需指定但愿被用来初始化 vector 的数组的开始地址以及数组最末元的下一位置来实现,例如:   
// 把 ia 的 6 个元素拷贝到 ivec 中  
vector< int > ivec( ia, ia+6 );  


被传递给ivec 的两个指针标记了用来初始化对象的值的范围,第二个指针老是指向要拷贝的末元素的下一位置,标记出来的元素范围也能够是数组的一个子集,例如 :

// 拷贝 3 个元素 ia[2], ia[3], ia[4] 
vector< int > ivec( &ia[ 2 ], &ia[ 5 ] );


3. 与内置数组不一样 vector 能够被另外一个 vector 初始化 或被赋给另外一个 vector 例如  
vector< string > svec; 
void init_and_assign() 

    // 用另外一个 vector 初始化一个 vector 
    vector< string > user_names( svec ); 
    // ... 
 
    // 把一个 vector 拷贝给另外一个 vector 
    svec = user_names; 
}

2、STL习惯用法

在 STL9中对vector 的习惯用法彻底不一样。咱们不是定义一个已知大小的 vector,而是定义一个空 vector  
vector< string > text;


1. 咱们向 vector 中插入元素,而再也不是索引元素,以及向元素赋值,例如 push_back()操做,就是在 vector 的后面插入一个元素下面的 while 循环从标准输入读入一个字符串序列并每次将一个字符串插入到 vector 中  
string word; 
while ( cin >> word ) { 
text.push_back( word ); 
// ... 
}

虽然咱们仍能够用下标操做符来迭代访问元素  
cout << "words read are: \n"; 
 
for ( int ix = 0; ix < text.size(); ++ix ) 
      cout << text[ ix ] << ' '; 
 
cout << endl; 
可是 更典型的作法是使用 vector 操做集中的begin()和 end()所返回的迭代器 iterator  
对 :
cout << "words read are: \n"; 
 
for ( vector<string>::iterator it = text.begin(); 
    it != text.end(); ++it ) 
           cout << *it << ' '; 
 
cout << endl 
iterator 是标准库中的类,它具备指针的功能 


*it; 
对迭代器解引用,并访问其指向的实际对象  
++it;

向前移动迭代器 it 使其指向下一个元素  

2. 注意 不要混用这两种习惯用法, 例如,下面的定义  
vector< int > ivec; 
定义了一个空vector 再写这样的语句  
ivec[ 0 ] = 1024; 
就是错误的 ,由于 ivec 尚未第一个元素,咱们只能索引 vector 中已经存在的元素 size()操做返回 vector 包含的元素的个数 。

3. 相似地 当咱们用一个给定的大小定义一个 vector 时,例如  :
vector<int> ia( 10 ); 
任何一个插入操做都将增长vector 的大小,而不是覆盖掉某个现有的元素,这看起来好像是很显然的,可是 下面的错误在初学者中并很多见 :
const int size = 7; 
int ia[ size ] = { 0, 1, 1, 2, 3, 5, 8 }; 
vector< int > ivec( size ); 
 
for ( int ix = 0; ix < size; ++ix ) 
    ivec.push_back( ia[ ix ]); 
程序结束时ivec 包含 14 个元素, ia 的元素从第八个元素开始插入。



在c++中,vector是一个十分有用的容器,下面对这个容器作一下总结。

1 基本操做

(1)头文件#include<vector>.

(2)建立vector对象,vector<int> vec;

(3)尾部插入数字:vec.push_back(a);

(4)使用下标访问元素,cout<<vec[0]<<endl;记住下标是从0开始的。

(5)使用迭代器访问元素.

vector<int>::iterator it;for(it=vec.begin();it!=vec.end();it++)
   cout<<*it<<endl;

(6)插入元素:    vec.insert(vec.begin()+i,a);在第i+1个元素前面插入a;

(7)删除元素:    vec.erase(vec.begin()+2);删除第3个元素

vec.erase(vec.begin()+i,vec.end()+j);删除区间[i,j-1];区间从0开始

(8)向量大小:vec.size();

(9)清空:vec.clear();

2

vector的元素不只仅可使int,double,string,还能够是结构体,可是要注意:结构体要定义为全局的,不然会出错。下面是一段简短的程序代码:

复制代码

#include<stdio.h>#include<algorithm>#include<vector>#include<iostream>using namespace std; typedef struct rect {    int id;    int length;    int width;

  //对于向量元素是结构体的,可在结构体内部定义比较函数,下面按照id,length,width升序排序。
  bool operator< (const rect &a)  const
    {
        if(id!=a.id)
            return id<a.id;
        else
        {
            if(length!=a.length)
                return length<a.length;
            else
                return width<a.width;
        }
    } }Rect;
int main() {    vector<Rect> vec;    Rect rect;    rect.id=1;    rect.length=2;    rect.width=3;    vec.push_back(rect);    vector<Rect>::iterator it=vec.begin();    cout<<(*it).id<<' '<<(*it).length<<' '<<(*it).width<<endl;    return 0; }

复制代码

 3  算法

(1) 使用reverse将元素翻转:须要头文件#include<algorithm>

reverse(vec.begin(),vec.end());将元素翻转(在vector中,若是一个函数中须要两个迭代器,

通常后一个都不包含.)

(2)使用sort排序:须要头文件#include<algorithm>,

sort(vec.begin(),vec.end());(默认是按升序排列,即从小到大).

能够经过重写排序比较函数按照降序比较,以下:

定义排序比较函数:

bool Comp(const int &a,const int &b)
{
    return a>b;
}
调用时:sort(vec.begin(),vec.end(),Comp),这样就降序排序。

#include <vector>
#include <iostream>
#include <string>
using namespace std;

void main()
{
#ifdef LIST_INIT
	// list initialization, articles has 3 elements
	vector<string> articles = { "a", "an", "the" };
#else
	string temp[] = { "a", "an", "the" };
	vector<string> articles(begin(temp), end(temp));
#endif

	vector<string> svec; // default initialization; svec has no elements
	vector<int> ivec;             // ivec holds objects of type int

	vector<vector<string>> file;  // vector whose elements are vectors
	vector<vector<int>> vecOfvec; // each element is itself a vector

	// all five vectors have size 0
	cout << svec.size() << " " << ivec.size() << " "
		<< " "
		<< file.size() << " " << vecOfvec.size() << endl;

	vector<int> ivec2(10);     // ten elements, each initialized to 0
	vector<int> ivec3(10, -1); // ten int elements, each initialized to -1
	vector<string> svec2(10);  // ten elements, each an empty string
	vector<string> svec3(10, "hi!"); // ten strings; each element is "hi!"
	cout << ivec2.size() << " " << ivec3.size() << " "
		<< svec2.size() << " " << svec3.size() << endl;

	// 10 is not a string, so cannot be list initialization
	vector<string> v1(10); // construct v1 with ten value-initialized elements
#ifdef LIST_INIT
	vector<string> v2{ 10 }; // ten elements value-initialized elements
#else
	vector<string> v2(10);
#endif
	vector<string> v3(10, "hi");  // ten elements with value "hi"
#ifdef LIST_INIT
	// again list initialization is not viable, so ordinary construction
	vector<string> v4{ 10, "hi" };  // ten elements with values "hi"
#else
	vector<string> v4(10, "hi");  // ten elements with values "hi"
#endif

	// all four vectors have size ten
	cout << v1.size() << " " << v2.size()
		<< " " << v3.size() << " " << v4.size() << endl;

#ifdef LIST_INIT
	vector<string> vs1{ "hi" }; // list initialization: vs1 has 1 element 
	vector<string> vs2{ 10 };   // ten default-initialized elements
	vector<string> vs3{ 10, "hi" }; // has ten elements with value "hi"
#else
	vector<string> vs1;
	vs1.push_back("hi"); // explicitly add the element; vs1 has 1 element 
	vector<string> vs2(10); // don't use curlies; 
	// vs2 has ten default-initialized elements
	vector<string> vs3(10, "hi"); // don't use curlies; 
	// vs3 has ten elements with value "hi"
#endif
	cout << vs1.size() << " " << vs2.size() << " " << vs3.size() << endl;

	vector<int> v5(10, 1);  // ten elements with value 1
#ifdef LIST_INIT
	vector<int> v6{ 10, 1 };  // two elements with values 10 and 1
#else
	vector<int> v6;
	v6.push_back(10);
	v6.push_back(1);
#endif
	cout << v5.size() << " " << v6.size() << endl;

#ifdef LIST_INIT
	// intention is clearer
	vector<int> alt_v3 = { 10 };    // one element with value 10
	vector<int> alt_v4 = { 10, 1 }; // two elements with values 10 and 1
#else
	vector<int> alt_v3;
	alt_v3.push_back(10);    // one element with value 10

	vector<int> alt_v4;
	alt_v4.push_back(10);
	alt_v4.push_back(1); // two elements with values 10 and 1
#endif
	cout << alt_v3.size() << " " << alt_v4.size() << endl;

	system("pause");
}


0 0  0 0
10 10 10 10
10 10 10 10
1 10 10
10 2
1 2
请按任意键继续. . .
相关文章
相关标签/搜索