codeproject,STL实际用法,不得不学学!

简介:      在STL实际应用过程当中,vector、list、map和set等都是常见的,理解和认识它们,是真正使用他们的基本。        vector     1:数组     int ar[10] = { 12, 45...

     在STL实际应用过程当中,vector、list、map和set等都是常见的,理解和认识它们,是真正使用他们的基本。   
    vector 
   1:数组
    int ar[10] = { 12, 45, 234, 64, 12, 35, 63, 23, 12, 55 }; 
    vector <int> vec1(ar, ar+10);
    char* str = "Hello World";
    vector <char> vec2(str, str+strlen(str)); 
    2:访问方式
    for (i=0; i<vec.size(); i++) { cout << vec[i]; } 


     set 
    A set is organized as a linked list, is faster than a vector on insertion and removal, but slightly slower on search and addition to end.
   set:事先根据一定的数据顺序将集合里面的值排列好,方便实现优化后的二分查找算法,提高搜索效率。如下代码;

set <string> strset;
set <string>::iterator si;
strset.insert("cantaloupes");
strset.insert("apple");
strset.insert("orange");
strset.insert("banana");
strset.insert("grapes");
strset.insert("grapes"); 
// This one overwrites the previous occurrence
for (si=strset.begin(); si!=strset.end(); si++) 
{  cout << *si << " ";  }

输出:apple cantalaoupes bannana grapes grapes  orangle

     map

      map采用更加人性化的方式表达一个数组或者是集合,但是有一点需要说明的就是,采用map管理的数据,该数据类型如果是用户自己定义的结构体、类,那么用户需要自己重新事先”=”运算符操作函数。

class CStudent
{
public :
int nStudentID;
int nAge;
public :
// Default Constructor - Empty
CStudent() { }
// Full constructor
CStudent(int nSID, int nA) { nStudentID=nSID; nAge=nA; }
// Copy constructor
CStudent(const CStudent& ob)
{ nStudentID=ob.nStudentID; nAge=ob.nAge; }
// Overload =
void operator = (const CStudent& ob)
{ nStudentID=ob.nStudentID; nAge=ob.nAge; }
};

int main(int argc, char* argv[])
{
map mapStudent;
mapStudent["Joe Lennon"] = CStudent(103547, 22);
mapStudent["Phil McCartney"] = CStudent(100723, 22);
mapStudent["Raoul Starr"] = CStudent(107350, 24);
mapStudent["Gordon Hamilton"] = CStudent(102330, 22);
// Access via the name
cout << "The Student number for Joe Lennon is " << (mapStudent["Joe Lennon"].nStudentID) << endl;

return 0;
}

    iterator

I said that iterators are pointers, but there is more. They look like pointers, act like pointers, but they are actually embedded in which the indirection operator (unary *) and -> have been overloaded to return a value from the container. It is a bad idea to store them for any length of time, as they usually invalid after a value has been added or removed from a container. They are something like handles in this regard. The plain iterator can be altered, so that the container is to be traversed in different ways:

  • iterator - For any container other than the vector, you can only step one at a time in a forward direction through the container. That is you can only use the ++ operator, not the -- or += operator on it. For vector only you can use any of +=, --, -=, ++, and all the comparison operators <, <=, >, >=, ==, !=.
  • reverse_iterator - If you want to step backwards instead of forwards through a non-vector container, replace iterator with reverse_iterator, begin() with rbegin(), and end() with rend(), ++ will then traverse backwards.
  • const_iterator - a forward iterator that returns a const value. Use this if you want to make it clear that this points to a read-only value.
  • const_reverse_iterator - a reverse iterator that returns a const value.

    Algorithms

     容器本身是不传递到算法,只需两个容器迭代器杂陈范围。这样,算法不仅限于直接的容器,而是由该特定的算法支持的迭代器。此外,很多时候你也可以专门为它设计自己函数。如下代码;

// Program: Test Score
// Purpose: To demonstrate the use of algorithm
// with respect to a vector of test scores

#include <algorithm>  // If you want to use an
// algorithm this is the header used.
#include <numeric>  // (For Accumulate)
#include <vector>
#include <iostream>
using namespace std;

int testscore[] = {67, 56, 24, 78, 99, 87, 56};

// predicate that evaluates a passed test
bool passed_test(int n)
{
    return (n >= 60);
}

// predicate that evaluates a failed test
bool failed_test(int n)
{
    return (n < 60);
}

int main(int argc, char* argv[])
{
    int total;
    // Initialize a vector with the data in the testscore array
    vector <int> vecTestScore(testscore,
        testscore + sizeof(testscore) / sizeof(int));
    vector <int>::iterator vi;
    // Sort and display the vector
    sort(vecTestScore.begin(), vecTestScore.end());
    cout << "Sorted Test Scores:" << endl;
    for (vi=vecTestScore.begin(); vi != vecTestScore.end(); vi++)
    {  cout << *vi << ", ";  }
    cout << endl;
    // Display statistics
    // min_element returns an _iterator_ to the
    // element that is the minimum value in the range
    // Therefor * operator must be used to extract the value
    vi = min_element(vecTestScore.begin(), vecTestScore.end());
    cout << "The lowest score was " << *vi << "." << endl;
    // Same with max_element
    vi = max_element(vecTestScore.begin(), vecTestScore.end());
    cout << "The highest score was " << *vi << "." << endl;
    // Use a predicate function to determine the number who passed
    cout << count_if(vecTestScore.begin(), vecTestScore.end(), passed_test) << " out of " << vecTestScore.size() << " students passed the test" << endl;
    // and who failed
    cout << count_if(vecTestScore.begin(),
        vecTestScore.end(), failed_test) << " out of " << vecTestScore.size() <<  " students failed the test" << endl;
    // Sum the scores
    total = accumulate(vecTestScore.begin(),
        vecTestScore.end(), 0);
    // Then display the Average
    cout << "Average score was " << (total / (int)(vecTestScore.size())) << endl;
    return 0;
}

输出结果:

Sorted Test Scores:
24, 56, 56, 67, 78, 87, 99,
The lowest score was 24.
The highest score was 99.
4 out of 7 students passed the test
3 out of 7 students failed the test
Average score was 66

    容器的嵌套使用

包含:class CParam { string name; string unit; vector <double> vecData; };

继承:class CParam : public vector <double> { string name; string unit; };

容器管理容器元素:To create a more complex data structure, you can nest a template within a template. It is best to typedef beforehand on the internal template as you will certainly need to use the inner template again.如下代码;

// Program: Vector of Vectors Demo
// Purpose: To demonstrate nested STL containers

#include <iostream>
#include <vector>

using namespace std;

typedef vector <int> VEC_INT;

int inp[2][2] = {{1, 1}, {2, 0}}; 
// Regular 2x2 array to place into the template
int main(int argc, char* argv[])
{
    int i, j;
    vector <VEC_INT> vecvec;
    // if you want to do this in all one step it looks like this
    // vector <vector <int> > vecvec;
    // Fill it in with the array
    VEC_INT v0(inp[0], inp[0]+2);  // passing two pointers
    // for the range of values to be copied to the vector
    VEC_INT v1(inp[1], inp[1]+2);
    vecvec.push_back(v0);
    vecvec.push_back(v1);
    for (i=0; i<2; i++)
    {
        for (j=0; j<2; j++)
        {
            cout << vecvec[i][j] << "  ";
        }
        cout << endl;
    }
    return 0;
}

输出结果:1  1 ,enter 2  0

      在STL中还有其他一些容器和方法,例如muti map等,但是只要掌握这集中最基本的容器,其他都可以进行扩展学习,该文希望对所有的来访问者有所帮助。

目录
相关文章
|
2天前
|
弹性计算 运维 搜索推荐
三翼鸟携手阿里云ECS g9i:智慧家庭场景的效能革命与未来生活新范式
三翼鸟是海尔智家旗下全球首个智慧家庭场景品牌,致力于提供覆盖衣、食、住、娱的一站式全场景解决方案。截至2025年,服务近1亿家庭,连接设备超5000万台。面对高并发、低延迟与稳定性挑战,全面升级为阿里云ECS g9i实例,实现连接能力提升40%、故障率下降90%、响应速度提升至120ms以内,成本降低20%,推动智慧家庭体验全面跃迁。
|
3天前
|
数据采集 人工智能 自然语言处理
3分钟采集134篇AI文章!深度解析如何通过云无影AgentBay实现25倍并发 + LlamaIndex智能推荐
结合阿里云无影 AgentBay 云端并发采集与 LlamaIndex 智能分析,3分钟高效抓取134篇 AI Agent 文章,实现 AI 推荐、智能问答与知识沉淀,打造从数据获取到价值提炼的完整闭环。
351 91
|
10天前
|
人工智能 自然语言处理 前端开发
Qoder全栈开发实战指南:开启AI驱动的下一代编程范式
Qoder是阿里巴巴于2025年发布的AI编程平台,首创“智能代理式编程”,支持自然语言驱动的全栈开发。通过仓库级理解、多智能体协同与云端沙箱执行,实现从需求到上线的端到端自动化,大幅提升研发效率,重塑程序员角色,引领AI原生开发新范式。
850 156
|
3天前
|
数据采集 缓存 数据可视化
Android 无侵入式数据采集:从手动埋点到字节码插桩的演进之路
本文深入探讨Android无侵入式埋点技术,通过AOP与字节码插桩(如ASM)实现数据采集自动化,彻底解耦业务代码与埋点逻辑。涵盖页面浏览、点击事件自动追踪及注解驱动的半自动化方案,提升数据质量与研发效率,助力团队迈向高效、稳定的智能化埋点体系。(238字)
257 156
|
4天前
|
域名解析 人工智能
【实操攻略】手把手教学,免费领取.CN域名
即日起至2025年12月31日,购买万小智AI建站或云·企业官网,每单可免费领1个.CN域名首年!跟我了解领取攻略吧~
|
11天前
|
机器人 API 调度
基于 DMS Dify+Notebook+Airflow 实现 Agent 的一站式开发
本文提出“DMS Dify + Notebook + Airflow”三位一体架构,解决 Dify 在代码执行与定时调度上的局限。通过 Notebook 扩展 Python 环境,Airflow实现任务调度,构建可扩展、可运维的企业级智能 Agent 系统,提升大模型应用的工程化能力。
|
人工智能 前端开发 API
前端接入通义千问(Qwen)API:5 分钟实现你的 AI 问答助手
本文介绍如何在5分钟内通过前端接入通义千问(Qwen)API,快速打造一个AI问答助手。涵盖API配置、界面设计、流式响应、历史管理、错误重试等核心功能,并提供安全与性能优化建议,助你轻松集成智能对话能力到前端应用中。
816 154