Codeproject, STL practical usage, have to learn!

Source: Internet
Author: User

In the practical application process of STL, vector, list, map, and set are common. Understanding and understanding them is the basis for truly using them.
Vector
1: Array
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: Access Method
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: Values in the set are arranged in a certain data order in advance, which facilitates the optimization of the Binary Search Algorithm and improves the search efficiency. The following code;

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 <"";}

Output: Apple cantalaoupes bannana grapes orangle

Map

Map uses a more user-friendly way to express an array or a set. However, it must be noted that the data managed by map is used. If the data type is a structure or class defined by the user, then you need to re-operate the function with the "=" operator.

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 ction through the container. That is you can only use++Operator, not--Or+=Operator on it.Vector onlyYou can use any+=,--,-=,++, And all the comparison Operators<,<=,>,>=,==,!=.
  • Reverse_iterator-If you want to step backwards instead of forwards through a non-vector container, replace iteratorreverse_iterator,begin()Withrbegin(), Andend()Withrend(),++Will then traverse backwards.
  • Const_iterator-A forward iterator that returnsconstValue. Use this if you want to make it clear that this points to a read-only value.
  • Const_reverse_iterator-A reverse iterator that returnsconstValue.

Algorithms

The container itself is not passed to the algorithm, and only two container iterators are needed. In this way, the algorithm is not limited to direct containers, but an iterator supported by the specific algorithm. In addition, you can also design your own functions for it. The following code;

// 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
// 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
// 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;
}

Output result:

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

Nested use of containers

Including: Class cparam {string name; string unit; vector <double> vecdata ;};

Inheritance: Class cparam: Public vector <double> {string name; string unit ;};

Container Management container element: to create a more complex data structure, you can nest a template within a template. It is besttypedefBeforehand on the internal template as you will certainly need to use the inner template again. The following code;

// Program: vector of vectors demo
// Purpose: to demonstrate nested STL containers

# Include <iostream>
# Include <vector>

Using namespace STD;

Typedef vector <int> vec_int;

Int indium [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 <int> vecvec;
// Fill it in with the array
Vec_int V0 (indium [0], indium [0] + 2); // passing two pointers
// For the range of values to be copied to the vector
Vec_int V1 (indium [1], indium [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;
}

Output result: 1 1, enter 2 0

There are other containers and methods in STL, such as Muti map. However, as long as you master the most basic containers in this set, others can perform extension learning, this article is intended to help all visitors.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.