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

     在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等,但是只要掌握这集中最基本的容器,其他都可以进行扩展学习,该文希望对所有的来访问者有所帮助。

时间: 2024-09-12 16:22:32

codeproject,STL实际用法,不得不学学!的相关文章

深入浅析STL vector用法_C 语言

本文关于stl vector用法的介绍非常详细,具体内容请看下文 介绍 这篇文章的目的是为了介绍std::vector,如何恰当地使用它们的成员函数等操作.本文中还讨论了条件函数和函数指针在迭代算法中使用,如在remove_if()和for_each()中的使用.通过阅读这篇文章读者应该能够有效地使用vector容器,而且应该不会再去使用C类型的动态数组了. Vector总览 vector是C++标准模板库中的部分内容,它是一个多功能的,能够操作多种数据结构和算法的模板类和函数库.vector之

STL——字符串用法详解

      字符串是程序设计中最复杂的变成内容之一.STL string类提供了强大的功能,使得许多繁琐的编程内容用简单的语句就可完成.string字符串类减少了C语言编程中三种最常见且最具破坏性的错误:超越数组边界:通过违背初始化或被赋以错误值的指针来访问数组元素:以及在释放了某一数组原先所分配的存储单元后仍保留了"悬挂"指针. string类的函数主要有:      Member functions (constructor) Construct string object (pu

[面试经]STL bitset用法总结

声明 #include < bitset > using std::bitset; bitset的定义和初始化 bitset<32> bitvec; //32位,全为0. 给出的长度值必须是常量表达式.正如这里给出的,长度值必须定义为整型字面值常量或是已用常量值初始化的整数类型的const对象. 这条语句把bitvec定义为含有32个位的bitset对象.和vector的元素一样,bitset中的位是没有命名的,程序员只能按位置来访问它们.位集合的位置编号从0开始,因此,bitve

浅谈c++中的stl中的map用法详解_C 语言

Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候,在编程上提供快速通道.这里说下map内部数据的组织,map内部自建一颗红黑树(一种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的,后边我们会见识到有序的好处. 下面举例说明什么是一对一的数据映射.比如一个班级中,每个学生的学号跟他的姓名就存在着一一

UVa 10420 List of Conquests (STL map)

10420 - List of Conquests Time limit: 3.000 seconds http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=98&page=show_problem&problem=1361 In Act I, Leporello is telling Donna Elvira about his master's long list of

PHP中list()函数用法实例简析_php技巧

本文实例讲述了PHP中list()函数用法.分享给大家供大家参考,具体如下: PHP中的list() 函数用于在一次操作中给一组变量赋值. 注意:这里的数组变量只能为数字索引的数组,且假定数字索引从 0 开始. list()函数定义如下: list(var1,var2...) 参数说明: var1      必需.第一个需要赋值的变量. var2,...  可选.更多需要赋值的变量. 示例代码如下: <?php //$arr=array('name'=>'Tom','pwd'=>'123

STL容器删除元素的陷阱

今天看Scott Meyers大师的stl的用法,看到了我前段时间犯的一个错误,发现我写的代码和他提到错误代码几乎一模一样,有关stl容器删除元素的问题,错误的代码如下:std::vector<struct> mFriendList;...std::vector<struct>::iterator iter = mFriendList.begin();for ( ; iter != mFriendList.end(); ++iter){    if (...)        mFr

C++语言 STL容器list总结_C 语言

在使用std::list<>链表时,难免会对数据进行添加删除操作.而遍历链表则有两种方式:通过索引访问,象数组一样处理:通过std::list<>::iterator链表遍历器进行访问 STL 中的list 就是一 双向链表,可高效地进行插入删除元素. list不支持随机访问.所以没有 at(pos)和operator[]. list 对象list1, list2 分别有元素list1(1,2,3),list2(4,5,6) .list< int>::iterator

深入理解C++中的vector类的用法及特性_C 语言

//<vector> template < class T, class Alloc = allocator<T> > class vector; 向量(Vector)是一个封装了动态大小数组的顺序容器(Sequence container).跟任意其它类型容器一样,它能够存放各种类型的对象.可以简单的认为,向量是一个能够存放任意类型的动态数组. vector类为内置数组提供了一种替代表示,与string类一样 vector 类是随标准 C++引入的标准库的一部分 ,为