容器:C++vector用法 VS C#list用法

C++中,用容器向量(vector)实现。容器向量也是一个类模板。
标准库vector类型使用需要的头文件:#include <vector>。vector 是一个类模板。不是一种数据类型,vector<int>是一种数据类型。Vector的存储空间是连续的,list不是连续存储的。

一、 定义和初始化
vector< typeName > v1;       //默认v1为空,故下面的赋值是错误的v1[0]=5;
vector<typeName>v2(v1);   //或v2=v1;或vector<typeName> v2(v1.begin(), v1.end());//v2是v1的一个副本,若v1.size()>v2.size()则赋值后v2.size()被扩充为v1.size()。
vector< typeName > v3(n,i);//v3包含n个值为i的typeName类型元素
vector< typeName > v4(n);//v4含有n个值为0的元素
int a[4]={0,1,2,3,3}; vector<int> v5(a,a+5);//v5的size为5,v5被初始化为a的5个值。后一个指针要指向将被拷贝的末元素的下一位置。
vector<int> v6(v5);//v6是v5的拷贝
vector< 类型 > 标识符(最大容量,初始所有值);

二、vector对象最重要的几种操作
1. v.push_back(t)   在容器的最后添加一个值为t的数据,容器的size变大。
    另外list有push_front()函数,在前端插入,后面的元素下标依次增大。
2. v.size()        返回容器中数据的个数,size返回相应vector类定义的size_type的值。v.resize(2*v.size)或                  

v.resize(2*v.size, 99) 将v的容量翻倍(并把新元素的值初始化为99)
3. v.empty()     判断vector是否为空
4. v[n]           返回v中位置为n的元素
5. v.insert(pointer,number, content)    向v中pointer指向的位置插入number个content的内容。
    还有v. insert(pointer, content),v.insert(pointer,a[2],a[4])将a[2]到a[4]三个元素插入。
6. v.pop_back()    删除容器的末元素,并不返回该元素。
7.v.erase(pointer1,pointer2) 删除pointer1到pointer2中间(包括pointer1所指)的元素。
   vector中删除一个元素后,此位置以后的元素都需要往前移动一个位置,虽然当前迭代器位置没有自动加1,
   但是由于后续元素的顺次前移,也就相当于迭代器的自动指向下一个位置一样。
8. v1==v2          判断v1与v2是否相等。
9. !=、<、<=、>、>=      保持这些操作符惯有含义。
10. vector<typeName>::iterator p=v1.begin( ); p初始值指向v1的第一个元素。*p取所指向元素的值。
      对于const vector<typeName>只能用vector<typeName>::const_iterator类型的指针访问。
11.   p=v1.end( ); p指向v1的最后一个元素的下一位置。
12. v.clear()      删除容器中的所有元素。12.v.clear()      删除容器中的所有元素。

13, v.swap()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// swap vectors
#include <iostream>
#include <vector>
void  main ()
{
   vector< int > foo (3,100);    // three ints with a value of 100
   vector< int > bar (5,200);    // five ints with a value of 200
   
   foo.swap(bar);
   
   cout <<  "foo contains:" ;
   for  (unsigned i=0; i<foo.size(); i++)
     cout <<  ' '  << foo[i];
   cout <<  '\n' ;
   
   cout <<  "bar contains:" ;
   for  (unsigned i=0; i<bar.size(); i++)
     cout <<  ' '  << bar[i];
   cout <<  '\n' ;
   
   return  0;
}
   
output:
foo contains: 200 200 200 200 200 
bar contains: 100 100 100

在这里补充一下Vector变量之间的赋值:

1
2
3
4
5
vector< int >a(5,0);       
vector< int >b(3,1);
//经过总结下面的语句可行:
a.clear();            
a=b;

#include<algorithm>中的泛函算法
搜索算法:find() 、search() 、count() 、find_if() 、search_if() 、count_if() 
分类排序:sort() 、merge() 
删除算法:unique() 、remove() 
生成和变异:generate() 、fill() 、transformation() 、copy() 
关系算法:equal() 、min() 、max() 
sort(v1.begin(),vi.begin()+v1.size/2); 对v1的前半段元素排序
list<char>::iterator pMiddle =find(cList.begin(),cList.end(),'A');找到则返回被查内容第一次出现处指针,否则返回end()。
int icount=count(v.begin(),v.end(),str);

三、内存管理与效率

1.使用reserve()函数提前设定容量大小,避免多次容量扩充操作导致效率低下。

vector<int> v;
v.reserve(1000);
for (int i = 1; i <= 1000; ++i) v.push_back(i);
这在循环中不会发生重新分配。

if (s.size() < s.capacity()) {
s.push_back('x');
}

2.使用“交换技巧”来修整vector过剩空间/内存

      有一种方法来把它从曾经最大的容量减少到它现在需要的容量。这样减少容量的方法常常被称为“收缩到合适(shrink to fit)”。该方法只需一条语句:vector<int>(ivec).swap(ivec);
表达式vector<int>(ivec)建立一个临时vector,它是ivec的一份拷贝:vector的拷贝构造函数做了这个工作。但是,vector的拷贝构造函数只分配拷贝的元素需要的内存,所以这个临时vector没有多余的容量。然后我们让临时vector和ivec交换数据,这时我们完成了,ivec只有临时变量的修整过的容量,而这个临时变量则持有了曾经在ivec中的没用到的过剩容量。在这里(这个语句结尾),临时vector被销毁,因此释放了以前ivec使用的内存,收缩到合适。

3.用swap方法强行释放STL Vector所占内存

1
2
    vector< int > v(4,0) ;
  vector< int >().swap(v);
1
v.swap(vector< int >());

/*或者{ std::vector<int> tmp = v;   v.swap(tmp);   }; //加大括号{ }是让tmp退出{ }时自动析构*/

统计vector中不同元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void  CKnn::setGroupName()
{
     string tem;
     vector<string>::iterator iter;
     for ( int  i=0;i<trainLabel.size();i++)
     {
         tem=trainLabel[i];
         iter=find(groupName.begin(),groupName.end(),tem);
         if (iter==groupName.end())
         {
             groupName.pop_back(tem);
         }
     }
}

1.vector 的数据的存入和输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<vector>
#include <iostream>    
using  namespace  std;   
void  main()  
{  
    int  i = 0;
    vector< int > v;   
    for ( i = 0; i < 10; i++ ) 
          v.push_back( i ); //把元素一个一个存入到vector中
     /* v.clear()*/  对存入的数据清空
    for ( i = 0; i < v.size(); i++ ) //v.size() 表示vector存入元素的个数
           cout << v[ i ]<<  "  " //把每个元素显示出来 
    cont << endl;
}

注:你也可以用v.begin()和v.end() 来得到vector开始的和结束的元素地址的指针位置。你也可以这样做:

vector::clear()函数的清空操作实际上执行的只是调用其析构函数,进行重置size等操作,实际内存中的数据并没有被清楚(这是为了提高效率)

当数组越界时,仍然会取到相应的数据。这时,可以采取:

1
2
3
vector<string> TempData;
       
TempData.swap( vector<string> () );

附:vector排序:sort(m_time.begin(),m_time.end());

vector插入N个初始为0的元素:m_time.insert(N,0);

将二维tem1的数据加入到tem2的后面:

1
2
3
4
5
vector< vector < double > >tem1;
       
vector< vector < double > >tem2;
       
tem2.insert(tem2.end(),tem1.begin(),tem1.end());

vector内元素随机打乱

vector <int> test;

random_shuffle(test.begin(), test.end());

2. 对于二维vector的定义。

1)定义一个10个vector元素,并对每个vector符值1-10。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<stdio.h>
#include<vector>
#include <iostream>
       
using  namespace  std;
       
void  main()
{
  int  i = 0, j = 0;
       
//定义一个二维的动态数组,有10行,每一行是一个用一个vector存储这一行的数据。
       
所以每一行的长度是可以变化的。之所以用到vector< int >(0)是对vector初始化,否则不能对vector存入元素。
  vector< vector< int > > Array( 10, vector< int >(0) ); 
       
for ( j = 0; j < 10; j++ )
  {
   for  ( i = 0; i < 9; i++ )
   {
    Array[ j ].push_back( i );
   }
  }
       
  for ( j = 0; j < 10; j++ )
  {
   for ( i = 0; i < Array[ j ].size(); i++ )
   {
    cout << Array[ j ][ i ] <<  "  " ;
   }
   cout<< endl;
  }
}

2)定义一个行列都是变化的数组。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<stdio.h>
#include<vector>
#include <iostream>
       
using  namespace  std;
       
void  main()
{
  int  i = 0, j = 0;
       
  vector< vector< int > > Array;
  vector<  int  > line;
  for ( j = 0; j < 10; j++ )
  {
   Array.push_back( line ); //要对每一个vector初始化,否则不能存入元素。
   for  ( i = 0; i < 9; i++ )
   {
    Array[ j ].push_back( i );
   }
  }
       
  for ( j = 0; j < 10; j++ )
  {
   for ( i = 0; i < Array[ j ].size(); i++ )
   {
    cout << Array[ j ][ i ] <<  "  " ;
   }
   cout<< endl;
  }
}

使用 vettor erase 指定元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include "iostream"
#include "vector"
using  namespace  std;
int    main()
{
     vector< int >   arr;
     arr.push_back(6);
     arr.push_back(8);
     arr.push_back(3);
     arr.push_back(8);
       
     for (vector< int >::iterator it=arr.begin(); it!=arr.end(); )
     {
         if (* it == 8)
         {
             it = arr.erase(it);
         }
         else
         {
             ++it;
         }
     }
       
     cout <<  "After remove 8:\n" ;
       
     for (vector< int >::iterator it = arr.begin(); it < arr.end(); ++it)
     {
         cout << * it <<  " " ;
     }
     cout << endl;
}



C# List<T>用法


所属命名空间:using System.Collections.Generic;

  List<T>类是  ArrayList 类的泛型等效类。 该类使用大小可按需动态增加的数组实现  IList<T> 泛型接口。 

泛型的好处: 它为使用 c#语言编写面向对象程序增加了极大的效力和灵活性。不会强行对值类型进行装箱和拆箱,或对引用类型进行向下强制类型转换,所以性能得到提高。

一、  List的基础、常用方法:

首先说明常用的二维用法为:

public List<List<String>> DatasetList { get; private set; }//C# 二维list变量的声明DatasetList = new List<List<string>>();//初始化List<string> rowdata = new List<string>();//先获取一个一维向量DatasetList.Add(rowdata);//将一维向量依次存储到二维向量中

1、List<T> mList = new List<T>();    
a.T为列表中元素类型,现在以string类型作为例子
如:  List<string> mList = new List<string>();

b.增加元素:List. Add(T item)    添加一个元素
如:mList.Add("赖炎滨");

c.插入元素:Insert(int index, T item);    在index位置添加一个元素
如:mList.Insert(1, "laiyanbin"); 

d.删除元素:  List. Remove(T item)       删除一个值
                如:mList.Remove("赖炎滨"); 

                List. RemoveAt(int index);   删除下标为index的元素

               如.:mList.RemoveAt(0); 

                List. RemoveRange(int index, int count);   从下标index开始,删除count个元素
                如.:mList.RemoveRange(3, 2); //超出删除的范围会出错
注:删除某元素后,其后面的元素下标自动跟进

e.判断是否存在List:List. Contains(T item)   得到的结果是返回true或false

f.排序:List. Sort ()   //默认是元素第一个字母按升序 

           给List里面元素顺序反转:
           List. Reverse ()   //可以与List. Sort ()配合使用,达到想要的效果

遍历List中元素:   
   foreach (T element in mList)  T的类型与mList声明时一样
            {
                 Console.WriteLine(element);
            } 

g.List清空:List. Clear ()
           如:mList.Clear();

h.获得List中元素数目:
           List. Count ()    返回int值

i.添加数组进List:string[] temArr = { Ha","Hunter", "Tom", "Lily", "Jay", "Jim", "Kuku", " "Locu" };
            mList.AddRange(temArr);

2、List<T> testList =new List<T> (IEnumerable<T> collection);
      以一个集合作为参数创建List
       E.g.: string[] temArr = { "Ha", "Hunter", "Tom", "Lily", "Jay", "Jim", "Kuku", "Locu" };
                  List<string> testList = new List<string>(temArr);

3、List与数组的相互转换
1.从string[]转List<string>
例如:string[] str={“1”,”2”};
List <string> list=new List<string>(str);
2.从List<string>转string[] 

例如:List<string> list=new List<string>;
String[] str=list.ToArray();

//ViewState["idlist"]转换成List<>

List<int> idlist=(List<int>)ViewState["idlist"]


  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值