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 <string cstudent>mapStudent; <br>mapStudent["Joe Lennon"] = CStudent(103547, 22); <br>mapStudent["Phil McCartney"] = CStudent(100723, 22); <br>mapStudent["Raoul Starr"] = CStudent(107350, 24); <br>mapStudent["Gordon Hamilton"] = CStudent(102330, 22); <br>// Access via the name <br>cout &lt;&lt; "The Student number for Joe Lennon is " &lt;&lt; (mapStudent["Joe Lennon"].nStudentID) &lt;&lt; endl; <br><br>return 0; <br>} </string>

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值