C++ stl 标准模版库

为什么要用这个stl  以及类似的boost了?   主要为了做到最大程度的数据结构和算法复用。

C++不像C#  java类的语言,语法很多用宏定义这类比较底层的封装,语法看起来比较绕脑。

有精力和时间的可以研究搜索 stl底层实现

其实学过C# java这类有虚拟机等解释器的语言,就比较容易理解了

说白了就是里面各类List  Queue   Map啊泛型的使用 ,泛型对照模版    List之类的对应了C++容器

里面也有一些Sort之类的对应算法    还有些细致的仿函数之类的 可以通过类似lambda语句来是实现。

编个例子直接看  :   经常用的队列  C++

#include <iostream>
#include <queue>

using namespace std;

queue<int> qtest;

int main()
{
	qtest.push(1);
	qtest.push(2);
	qtest.push(3);
	qtest.push(4);

	while (!qtest.empty())
	{
		cout << qtest.front() << endl;
		qtest.pop();
	}
}

运行结果:

1
2
3
4

--------------------------------------------------------------------------------------------------------

链表List  C++   方几个数据   并且加上排序


#include <iostream>
#include <list>

using namespace std;

list<int> list_test;

struct sortfun {
	bool operator()(int a1, int a2) {
		return a1 > a2;    //若改为>,则变为降序
	}
};

int main()
{
	list_test.push_front(1);
	list_test.push_front(2);
	list_test.push_front(3);
	list_test.push_front(4);


	while (!list_test.empty())
	{
		cout << list_test.back() << endl;
		list_test.pop_back();
	}

	//换个方式
	cout << "排序  并使用迭代的方式获取数据  " << endl;

	list_test.push_front(1);
	list_test.push_front(3);
	list_test.push_front(2);
	list_test.push_front(4);

	//升序是默认的  
	//list_test.sort();
	//使用重载的仿函数来做
	list_test.sort(sortfun());

	for (list<int>::iterator it = list_test.begin(); it != list_test.end(); it++)
	{
		cout << *it << endl;
	}

}

运行结果

1
2
3
4
排序  并使用迭代的方式获取数据
4
3
2
1

----------------------------------------------------------------------

最后放个 C# 的  注意不是C++  比较看看 是不是很类似呢?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> listTest = new List<int>(new int[4]);

            //如果上面不new int[4]  也可以用listTest.add(xxx)的形式
            listTest[0] = 1;
            listTest[1] = 3;
            listTest[2] = 2;
            listTest[3] = 4;

            foreach (var item in listTest){
                Console.WriteLine(item);
            }

            Console.WriteLine("降序开始");

            listTest.Sort((x, y) => -x.CompareTo(y));

            foreach (var item in listTest){
                Console.WriteLine(item);
            }

        }
    }
}

结果:

1
3
2
4
降序开始
4
3
2
1

------------------------------------------------------------------

java和C#差不多 就不列了

总之先明白要干什么,比较下 还是很容易上手的  目的都是一个 :

方便的使用通用的数据结构,以及相应的一些排序啊 比较啊 逻辑 通用算法,从而让自己绕开这些底层数据结构的设计  。  

其它的容器  和 算法 包括类作为模版或泛型的例子 也基本类似

最后转个讲解的比较详细的文章:

C++中STL用法超详细总结_一只大笨猫的博客-CSDN博客_c++ stl

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值