c++基础学习笔记(三)

----部分摘自c++菜鸟教程----

map用法

map是C++中的一个标准容器,她提供了很好一对一的关系,在一些程序中建立一个map可以起到事半功倍的效果。

map最基本的构造函数;

map<string , int >mapstring; map<int ,string >mapint;

map<sring, char>mapstring; map< char ,string>mapchar;

map<char ,int>mapchar; map<int ,char >mapint;

map添加数据;
   map<int ,string> maplive;  
   	maplive.insert(pair<int,string>(102,"aclive"));
   	maplive.insert(map<int,string>::value_type(321,"hai"));
   	maplive[112]="April";//map中最简单最常用的插入添加!

map中元素的查找:

find()函数返回一个迭代器指向键值为key的元素,如果没找到就返回指向map尾部的迭代器。

 map<int ,string >::iterator l_it;; 
   l_it=maplive.find(112);
   if(l_it==maplive.end())
                cout<<"we do not find 112"<<endl;
   else cout<<"wo find 112"<<endl;
map中元素的删除:

如果删除112;

 map<int ,string >::iterator l_it;;   
   l_it=maplive.find(112);
   if(l_it==maplive.end())
        cout<<"we do not find 112"<<endl;
   else  maplive.erase(l_it);  //delete 112;
map中 swap的用法:

Map中的swap不是一个容器中的元素交换,而是两个容器交换;

示例:

#include <map> 
#include <iostream>
using namespace std;
int main()
{
	map <int, int> m1, m2, m3;
	map <int, int>::iterator m1_Iter;
	m1.insert(pair <int, int>(1, 10));
	m1.insert(pair <int, int>(2, 20));
	m1.insert(pair <int, int>(3, 30));
	m2.insert(pair <int, int>(10, 100));
	m2.insert(pair <int, int>(20, 200));
	m3.insert(pair <int, int>(30, 300));
	cout << "The original map m1 is:";
	for (m1_Iter = m1.begin(); m1_Iter != m1.end(); m1_Iter++)
		cout << " " << m1_Iter->second;
	cout << "." << endl;
	// This is the member function version of swap
	//m2 is said to be the argument map; m1 the target map
	m1.swap(m2);
	cout << "After swapping with m2, map m1 is:";
	for (m1_Iter = m1.begin(); m1_Iter != m1.end(); m1_Iter++)
		cout << " " << m1_Iter->second;
	cout << "." << endl;
	cout << "After swapping with m2, map m2 is:";
	for (m1_Iter = m2.begin(); m1_Iter != m2.end(); m1_Iter++)
		cout << " " << m1_Iter->second;
	cout << "." << endl;
	// This is the specialized template version of swap
	swap(m1, m3);
	cout << "After swapping with m3, map m1 is:";
	for (m1_Iter = m1.begin(); m1_Iter != m1.end(); m1_Iter++)
		cout << " " << m1_Iter->second;
	cout << "." << endl;
}
map的sort问题:

Map中的元素是自动按key升序排序,所以不能对map用sort函数:

示例:

 #include <map>  #include <iostream>
 using namespace std;
 int main( )
 {
   map <int, int> m1;
   map <int, int>::iterator m1_Iter;
   m1.insert ( pair <int, int>  ( 1, 20 ) );
   m1.insert ( pair <int, int>  ( 4, 40 ) );
   m1.insert ( pair <int, int>  ( 3, 60 ) );
   m1.insert ( pair <int, int>  ( 2, 50 ) );
   m1.insert ( pair <int, int>  ( 6, 40 ) );
   m1.insert ( pair <int, int>  ( 7, 30 ) );
   cout << "The original map m1 is:"<<endl;
   for ( m1_Iter = m1.begin( ); m1_Iter != m1.end( ); m1_Iter++ )
      cout <<  m1_Iter->first<<" "<<m1_Iter->second<<endl;
}
map的基本操作函数:

C++ Maps是一种关联式容器,包含“关键字/值”对

名称作用
begin()返回指向map头部的迭代器
clear()删除所有元素
count()返回指定元素出现的次数
empty()如果map为空则返回true
end()返回指向map末尾的迭代器
equal_range()返回特殊条目的迭代器对
erase()删除一个元素
find()查找一个元素
get_allocator()返回map的配置器
insert()插入元素
key_comp()返回比较元素key的函数
lower_bound()返回键值>=给定元素的第一个位置
max_size()返回可以容纳的最大元素个数
rbegin()返回一个指向map尾部的逆向迭代器
rend()返回一个指向map头部的逆向迭代器
size()返回map中元素的个数
swap()交换两个map
upper_bound()返回键值>给定元素的第一个位置
value_comp()返回比较元素value的函数

vector使用方法

在c++中,vector是一个十分有用的容器。它能够像容器一样存放各种类型的对象,简单地说,vector是一个能够存放任意类型的动态数组,能够增加和压缩数据。

使用vector注意事项:

1、如果你要表示的向量长度较长(需要为向量内部保存很多数),容易导致内存泄漏,而且效率会很低;

2、Vector作为函数的参数或者返回值时,需要注意它的写法:

double Distance(vector<int>&a, vector<int>&b)

其中的“&”绝对不能少!!!

实例:

vectortest;//建立一个vector,int为数组元素的数据类型,test为动态数组名

简单的使用方法如下:

vector<int>test;//建立一个vector
test.push_back(1);
test.push_back(2);//把1和2压入vector,这样test[0]就是1,test[1]就是2

自己见到的实例:

vector<vector<Point2f> > points; //定义一个二维数组
points[0].size();  //指第一行的列数
1 、基本操作

(1)头文件#include.

(2)创建vector对象,vector 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();

特别提示:这里有begin()与end()函数、front()与back()的差别

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

reverse(vec.begin(),vec.end());将元素翻转,即逆序排列!

(在vector中,如果一个函数中需要两个迭代器,一般后一个都不包含)

(2)使用sort排序:需要头文件#include,

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

可以通过重写排序比较函数按照降序比较,如下:

定义排序比较函数:

bool Comp(const int &a,const int &b)
{
    return a>b;
}

调用时:sort(vec.begin(),vec.end(),Comp),这样就降序排序。

输出Vector的中的元素

vector vecClass;

int nSize = vecClass.size();

//打印vecClass,方法一:

for(int i=0;i<nSize;i++)    
{    
   cout<<vecClass[i]<<"     ";    
}    
   cout<<endl;   

需要注意的是:以方法一进行输出时,数组的下表必须保证是整数。

//打印vecClass,方法二:

for(int i=0;i<nSize;i++)    
{    
   cout<<vecClass.at(i)<<"     ";    
}    
   cout<<endl;    

//打印vecClass,方法三:输出某一指定的数值时不方便

for(vector<float>::iterator it = vecClass.begin();it!=vecClass.end();it++)    
{    
    cout<<*it<<"   ";    
}    
    cout<<endl;    
二维数组的使用:
#include "stdafx.h"  
#include <cv.h>  
#include <vector>   
#include <iostream>   
using namespace std;  
int main()  
{  
    using namespace std;  
    int out[3][2] = { 1, 2,   
             3, 4,  
            5, 6 };  
    vector <int*> v1;  
    v1.push_back(out[0]);  
    v1.push_back(out[1]);  
    v1.push_back(out[2]);  
    cout << v1[0][0] << endl;//1  
    cout << v1[0][1] << endl;//2  
    cout << v1[1][0] << endl;//3  
    cout << v1[1][1] << endl;//4  
    cout << v1[2][0] << endl;//5  
    cout << v1[2][1] << endl;//6  
    return 0;  
}  

​ 函数模板

  • template关键字
template<class T>//类型参数化
//或者
template<typename T>
void MySwap(T& a, T& b)
{
	T temp;		//此处的T可以表示任意数据类型int、double、float......
	temp = a;	a = b;	b = temp;
}
void MySwap(int& a, int& b)
{
	int temp;		
	temp = a;	a = b;	b = temp;
}

void test01()
{
	int a = 10, b = 20;
	cout << "a:" << a << "  b:" << b << endl;
	MySwap(a, b);
	cout << "a:" << a << "  b:" << b << endl;

	double c = 10.12, d = 20.34;
	cout << "c:" << c << "  d:" << d << endl;
	MySwap(c, d);
	cout << "c:" << c << "  d:" << d << endl;
}
int main()
{
	test01();
	return 0;
}
a:10  b:20
a:20  b:10
c:10.12  d:20.34
c:20.34  d:10.12
  • 函数模板不可以进行自动类型转换,需要精确指定参数类型;普通函数会自动进行参数类型转换
  • 函数模板可以进行重载
  • c++编译器优先考虑普通函数,MySwap<>(a, b);可以强制执行函数模板
类模板
  • 类模板必须显式的指定类型
  • 函数模板必须严格类型匹配
#include<iostream>
#include<string>
using namespace std;

template<class T1, class T2>
class Person
{
public:
	Person(T1 id, T2 age)
	{
		this->m_Id = id;
		this->m_Age = age;
	}
	void Show()
	{
		cout << m_Id << " " << m_Age << endl;
	}
public:
	T1 m_Id;
	T2 m_Age;
};
int main()
{
	Person<string, int> p("aaa", 20);//显式的指定类型
	p.Show();
	return 0;
}
派生类
template<class T>
class Person
{
public:
    Person(T age)
    {
        this->m_Age = age;
    }
public:
    T m_Age;
};

template<class T>
class SubPerson : public Person<T>	//此处 <T> 不能丢
{
	...
};
类模板.h和.cpp分离
//头文件	Person.h
#pragma once
#include<iostream>
using namespace std;

template<class T>
class Person
{
public:
    Person(T age);
    void Show();
public:
    T m_Age;
};

//源文件	Person.cpp	在类模板文件中一般将 .cpp 改为 .hpp
#include"Person.h"

template<calss T>
Person<T>::Person(T age)	//此处 <T> 不能丢
{
    this->m_Age = age;
}
template<class T>
void Person<T>::Show()	//此处 <T> 不能丢
{
    cout << m_Age << endl;
}

//源文件	demo.cpp
#include"Person.h"						//******
#include<iostream>						   / \
using namespace std;						|
										    |
int main()								    |
{										    |
    Person<int> p(20);						|
    p.Show();	//此时编译报错,解决方法:将******处的语句改为 #include"Person.hpp"
    return 0;
}

类模板中的static关键字
template<class T>
class Person
{
public:
    static int a;
};
//类外初始化
template<class T> int Person<T>::a = 0;

int main()
{
    Person<int> p1, p2, p3;
    Person<char> pp1, pp2, pp3;
    p1.a = 10;
    pp1.a = 20;
    cout << p1.a << " " << p2.a << " " << p3.a << endl;
    cout << pp1.a << " " << pp2.a << " " << pp3.a << endl;
	return 0;
}

10 10 10
20 20 20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值