STL learning: STL library vector, string, set, map usage, stlvector

Source: Internet
Author: User

STL learning: STL library vector, string, set, map usage, stlvector
Common Methods

 

Vector

1. Random Access, element insertion at the end; 2. Automatic Memory Management; 3. header file # include <vector>

1. Create a vector object

One-dimensional:

(1) vector <int> v1;

(2) vector <int> v2 (10); // 10 elements, initially 0

(3) vector <int> v3 (10, 4); // 10 elements, initially 4

(4) vector <int> v4 (v3); // copy

(5) vector <int> v5 = v4; // copy

(6) vector <int> v6 (v. begin (), v. end ());

(7) int a [4] = {1, 2, 3}; vector <int> v7 (a, a + sizeof (a)/sizeof (a [0]); // similar to the above

(8) string str [] = {"abc", "def", "ghi"}; vector <string> v8 (str, str + sizeof (str) /sizeof (string); // similar to the above

(9) char * s [] = {"abc", "def", "ghi"}; vector <string> v9 (s, s + sizeof (s) /sizeof (int); // similar to the above

Two-dimensional:

(1) int n = 3, m = 4; vector <int> matrix (n, m ); // create a two-dimensional vector object with n rows and m columns whose initial values are 0

(2) vector <int> mat (n, vector <int> (m, 9); // The initial value is 9.

Note: mat. size (); mat [0]. size ();

2. Tail element expansion: v. push_back (elem );

3. subscript access: v [index] = elem; cout <v [index]; // traverse the two-dimensional vector below

int a[]={1,2,3,4,5};vector<int>v(a,a+sizeof(a)/sizeof(a[0]));vector<vector<int>>mat(3,v);for(size_t i =0; i<mat.size(); i++){    for(size_t j=0; j<mat[i].size(); j++)        cout<<mat[i][j];    cout<<endl;}

4. v. at (index) Access: mat. at (1 ). at (2) = 433; cout <mat. at (1 ). at (2); // two-dimensional example

5. Use the iterator to access and traverse:

Begin (), end (), rbegin (), rend (): The iterator at the position of the first element returned by begin (); end () the returned iterator is the next element position of the last element. Rbegin () and rend () are opposite to them.

Vector <int>: iterator it; for (it = v. begin (); it! = V. end (); it ++) cout <* it <""; // use auto, and the code is concise for (auto I = v. begin (); I! = V. end (); I ++) cout <* I <""; // The Reverse traversal iterator is reverse_iteratorfor (auto I = v. rbegin (); I! = V. rend (); I ++) cout <* I <"";
// These two traversal methods are also available for other classes
Int arr [5] = {10, 20, 30, 40, 50}; vector <int> vec (arr, arr + sizeof (arr)/sizeof (arr [0]); cout <(* vec. begin () + 2 <endl; // 12 cout <* (vec. begin () + 2) <endl; // 30 cout <* vec. begin () + 2 <endl; // 12 // * The operator priority is greater than the + operator priority.

6. insert an element (insert a data before the iterator position) v. insert (pos, elem) v. insert (pos, n, elem) v. insert (pos, beg, end)

Vector <int> v (10); int a [] = {1, 2, 3, 4, 5, 6, 7}; vector <int> v1 (a, a + sizeof () /sizeof (a [0]); v. insert (v. begin () + 1, v1.begin (), v1.begin () + 3); for (auto I = v. begin (); I! = V. end (); I ++) cout <* I; cout <* (v1.begin () + 3) <endl; // v. insert (pos, beg, end); copy interval: [beg, end)

7. Delete v. erase (pos) v. erase (beg, end) of the element ). The interval is [beg, end ).

8. Use the reverse Sorting algorithm and header file <algorithm>

reverse(v.begin(),v.end());

 

9. sort sorting

(1) sort (v. begin (), v. end (); // The default value is ascending.

(2) sort (v. begin (), v. end (), cmp); // sort by cmp conditional Function

10. size () and capacity (), reserve () and resize ()

(1) capacity refers to capacity and size refers to the number of actual elements. Size <= capacity

(2) When the element exceeds the capacity, the capacity function increases.

(3) Whether the return vector of the empty () method is null indicates the actual number of data.

(4) reserve () and resize () are respectively resetting capacity and size. When an exception occurs, the vector object is automatically resized.

The following table Source: http://blog.csdn.net/phoebin/article/details/3864590 string

Header file <string>

1. Create a string object: string s;

2. assign a value to the string object:

(1) s = "abc ";

(2) assign a character pointer to a string object.

char *c1="abcde";char c2[]={'f','g','h','\0'};string s=c1;s+=c2;cout<<s<<endl;

3. Add characters and strings at the end

String s; s + = 'a'; s. push_back ('B'); // note that the string s cannot be added using this method. pop_back (); s + = "cde"; s. append ("f"); // you cannot use this method to add the cout character <s <endl;

4. The insert () method inserts a character before the iterator position ). S. insert (pos, char), s. insert (pos, n, elem) s. insert (pos, beg, end)

5. subscript access.

6. delete an element. (1) s = ""; (2) earse ()

7. Return length. S. length () or s. size ()

8. replace the characters of the string object. Common replace (beginIndex, len, str)

String s; s = "abc123456"; s. replace (3rd, "good"); // replace the three consecutive characters with "good ", replace "abc" with "good" cout <s <endl;

9. Search for elements or substrings of a string object. Find ()

// The find () method can be used to find characters and strings. If the string: npos value (4294967295) is not found, the return value must match the complete string, find_first_of can be (group) string s = "acbac"; cout <s. find ("AB") <endl; // 2, returns the first subscript OF THE STRING cout <s. find_first_not_of ('') <endl; // 2 cout <s. find_first_of ("1234567a") <endl; // 2, cout <s. find_last_not_of ('') <endl; // 4 cout <s. find_last_of ('C') <endl; // 4 cout <s. rfind ('A') <endl; // 4, returns the first int a = s. find ("AB"); printf ("% d", a = string: npos); // 1, not found. npos is returned.

10. String comparison. Compare ()

// If it is greater than the other party, 1 is returned. If it is smaller than the other party,-1 is returned. If it is the same (equal) as the other party, 0 is returned. String s1 = "12345"; string s2 = "fgger"; cout <s1.compare (s2) <endl; // you can directly use the comparison operator bool isq = s1 = s2; cout <isq <endl; isq = "1" = "1 "; cout <isq <endl;

11. Use reverse to reverse sort string objects. Reverse header file <algorithm>, reverse (s. begin (), s. end ());

12. Mutual conversion between values

// Convert numeric values to the string C ++ method. Use the ostringstream stream double d = 1.34 in <sstream>; ostringstream o; if (o <d) // input the value d to the cout stream <o. str () <endl; else cout <"conversion error" <endl; // string to numeric C ++ method, use the istringstream stream in <sstream> string s3 = "1234.234"; istringstream I (s3); // put the string into the stream double d2; if (I> d2) // Output d cout from the stream <d2 <endl; else d2 = 0.0; // convert the value to the string: C method, and use the sprintf function char B [10]; string a; sprintf (B, "% d", 1975); // The sprintf cannot be printed directly to the string. The sprintf is the C function a = B; cout <a <endl;

13. printf prints the string object. Use the c_str () method (printf is a C function, and string belongs to C ++)

printf(s.c_str()); 
Printf ("% s", s); // This is wrong

14. Others

Understanding how to use C functions sscanf () and sprintf ()

 

Set

The set collection container implements the balanced binary Tree data structure of the Red-Black Tree. When an element is inserted, it automatically adjusts the arrangement of Binary Trees, place this element in a proper position to ensure that the key value of each subtree root node is greater than the key value of all nodes in the left subtree, and less than the key value of all nodes in the right subtree. In addition, make sure that the height of the Left subtree of the root node is the same as that of the right subtree. In this way, the height of the binary tree is the minimum and the retrieval speed is the fastest. Note that it does not insert elements with the same key value repeatedly, and ignore the elements. The internal structure of multiset, map, and multimap is also a balanced binary search tree.

Set elements cannot be repeated, and multiset elements can be repeated.

Unordered_set, header file <unordered_set>

Set header file <set>

1. Create a set object. Set <int> s;

2. Insert an element. The insert (elem) method is used to insert elements into the set in sequence. If an element is inserted repeatedly, the subsequent insertion is invalid, but no error occurs.

3. Reverse traversal of elements (refer to reverse traversal of vector or the following code ).

5. delete an element. S. erase (elem); clear s. clear () of the element ();

6. Search for elements. Use find (). If the queried key value is found, the iterator position of the key value is returned. Otherwise, a position after the last element of the set, that is, end (), is returned ().

Set <int> s; s. insert (4); s. insert (3); s. insert (7); s. insert (1); s. insert (3); // duplicate element, s. erase (3); // erase element 3 from auto it = s. find (3); // search for element 3. Locate the position of the returned iterator. Otherwise, return s. end () if (it! = S. end () cout <"found" <* it <endl; else cout <"not found! "<Endl; // element set in the reverse traversal set <int>: reverse_iterator I; for (I = s. rbegin (); I! = S. rend (); I ++) cout <* I <"";

7. Custom comparison functions. When insert () is used to insert an element into a set, the set puts the element to the set Node Based on the set comparison function. When defining a set, if no comparison function is specified, the default comparison function is used, that is, the elements are inserted in sequence from small to large key values. In many cases, you need to write a comparison function by yourself. There are two methods to compile a comparison function.
(1) If the element is not a struct, You can compile a comparison function.

// Custom comparison function myComp, reload the "()" operator struct myComp {bool operator () (const int & a, const int & B) {if (! = B) return a> B; else return a> B ;}}; int main () {set <int, myComp> s; s. insert (4); s. insert (3); s. insert (7); s. insert (1); s. insert (3); // duplicate element, cannot insert s. erase (3); // erase element 3 from set <int, myComp>: iterator I; for (I = s. begin (); I! = S. end (); I ++) cout <* I <""; system ("pause"); return 0 ;}

(2) If the element is a struct, you can directly write the comparison function in the structure.

Struct Info {string name; float score; // reload the "<" operator, custom sorting rule bool operator <(const Info &) const {// sort by score in ascending order. If you want to arrange from small to large, use the ">" sign. Return. score <score ;}}; int main () {// Sets object s that defines the element type as the Info struct. Currently, no element set <Info> s is available; // define the Info element of the Info type; // Insert the info element. name = "Jack"; info. score = 80.5; s. insert (info); info. name = "Tomi"; info. score = 20.5; s. insert (info); info. name = "Nacy"; info. score = 60.5; s. insert (info); set <Info >:: iterator it; // defines the forward iterator for (it = s. begin (); it! = S. end (); it ++) {cout <(* it ). name <":" <(* it ). score <endl;} system ("pause"); return 0 ;}
Map

The element data of the map ing container is composed of a key value and a ing data.
Has a one-to-one ing relationship. Key values cannot be repeated and sorted by key value. Multimap multi- ing container with repeated key values

Header file <map>

Unordered_set, header file <unordered_map>

1. map creation, element insertion, and traversal access

Map <int, string> m; m [1] = "a"; m [4] = "B"; m [3] = "c "; m [7] = "e"; m [6] = "f"; m [5] = "g"; // Insert elements with pair // map <int, string> mp; pair <int, string> p; p = make_pair (1, "q"); mp. insert (p); auto mb = mp. begin (); auto me = mp. end (); cout <mb-> first <; cout <(* mb ). second <endl; cout <(* mp. begin ()). first; cout <(* mp. begin ()). second; for (auto I = m. begin (); I! = M. end (); I ++) // traverses the output cout <(* I ). first <":" <(* I ). second <endl;

2. delete an element. M. erase (key)

3. Reverse traversal. (Refer to vector)

4. Search for elements. Find (), (refer to set)

5. Custom comparison functions. (Two types, struct, or non-struct, refer to set)


Stl string, vector, map problems, Optimization

After reading it, I found that you still lack much understanding and use of C ++.

A variety of inefficient writing methods for the entire code segment. For example, the split function returns a vector by value, which will cause two full copies of the vector, which is a great waste, parameters are passed by value rather than by const reference. String operations use a mix of C and C ++ processing methods. strings are used for a while and char arrays are used. Is a bad habit. In addition, stream in C ++ is used, but stream in C ++ is less efficient than FILE in C.
In addition, your encoding style is not very good, and the variable name does not have any meaning, which is hard for others to understand.

The above are some writing habits, and your code is very inefficient in terms of algorithms.
Why do you traverse vec3 every time in a loop? Just to count, why not count in the while loop at the beginning? In this way, you only need to traverse vec3 in the whole program, and the time complexity will immediately decrease by a magnitude.
And your vec4, which is also very inappropriate. From the perspective of your code, your vec4 is only for a repetitive test. Why do we need a vector? In this case, it is better to use set. The search in the vector is very slow. The time complexity O (n). To find an element in the set, only O (logn) is required ), faster than one level.

I feel that you still lack a lot of knowledge about the standard containers in STL, and you have not figured out the applicability of these containers. I still need to add more supplements.

Download the source code of stl vector in the c ++ standard library

No. For example, if you use vector, you must import the vector, right? So there is such a sentence at the beginning of the file: # include <vector>, right-click on the vector, there will be an option to open the file or go to the definition, and the selection will open. Of course, I am talking about integrated development environment.

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.