C # STL in comparison with C ++

Source: Internet
Author: User

Introduction: Program into Your Language, Not in It-code Daquan. How to program in a language? I think there are three steps: Get familiar with it, know its limitations, and expand it. How to get familiar with it? Needless to say, it is natural to read and read data and write more data. How can we know its limitations? In this step, we can only compare things. Everything has its own limitations, and nothing is perfect (except the God Smile ). Here, I use C # And C ++ for comparison and try to outline some conceptual differences between C # And C ++. How to expand? I am trying Embarrassed smile. The STL of C ++ contains six major components: container, Iterators, algorithm (Algorithms), functors, and Adapters), configurator (Allocators ). The container acquires the data storage space through the configurator, and the algorithm accesses the container content through the iterator. The Imitation function assists the algorithm in completing different operation policies, and the adapter is used to modify or intercept functions. This complete set of cooperation allows us to have full control over the addition, query, modification, and deletion of data in the memory. (I would like to draw a picture here, but I have been looking for a long time and cannot find a good tool. Can anyone share some good tools such as painting ?) In the container STL, the most common containers are vector, list, map, and set. In C #, the corresponding containers are: List, Dictionary List, Dictionary, and HashSet. A single view of the container actually abstracts some logical structures and reflects different physical storage structures in the memory according to different logical needs. The abstraction of C ++ and C # is no different. Of course, the implementation of C ++ is very different. This can be seen through code writing. The C ++ code is as follows: # include <iostream> # include <vector> # include <list> # include <map> # include <set> # include <algorithm> using namespace std; int main () {vector <int> vec; list <int> lst; map <int, int> mp; set <int> st; for (int I = 0; I <10; ++ I) {vec. push_back (I); lst. push_back (I); mp. insert (make_pair (I, I); st. insert (I) ;}cout <"vector:" <endl; vector <int >:: const_iterator iterVec (vec. begin (); while (I TerVec! = Vec. end () {cout <* iterVec <endl; ++ iterVec;} cout <"\ nlist:" <endl; list <int> :: const_iterator iterLst (lst. begin (); while (iterLst! = Lst. end () {cout <* iterLst <endl; ++ iterLst;} cout <"\ nmap:" <endl; map <int, int> :: const_iterator iterMap (mp. begin (); while (iterMap! = Mp. end () {cout <"Key =" <iterMap-> first <"Value =" <iterMap-> second <endl; ++ iterMap ;} cout <"\ nset:" <endl; set <int>: const_iterator iterSet (st. begin (); while (iterSet! = St. end () {cout <* iterSet <endl; ++ iterSet ;}} C # The Code is as follows: using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using System. collections; using System. net. sockets; using System. net; namespace ConsoleApplication1 {class Program {static void Main (string [] args) {List <String> list = new List <String> (); shortlist <String> shortlist = new Li NkedList <String> (); Dictionary <Int32, String> dic = new Dictionary <Int32, String> (); HashSet <String> set = new HashSet <String> (); for (int I = 0; I <10; ++ I) {list. add (I. toString (); returns list. addLast (I. toString (); dic. add (I, I. toString (); set. add (I. toString ();} Console. writeLine ("List:"); foreach (var item in list) {Console. writeLine (item);} Console. writeLine ("\ nequallist:"); foreach (Var item in lifecycle list) {Console. writeLine (item);} Console. writeLine ("\ nDictionary:"); foreach (var item in dic) {Console. writeLine ("Key = {0}, Value = {1}", item. key, item. value);} Console. writeLine ("\ nHashSet:"); foreach (var item in set) {Console. writeLine (item) ;}}} C ++ does not have a built-in foreach Statement (which seems to be included in the new standard ?), So it uses the iterator to help it complete iteration. C # is very convenient. It completes this function at the syntax level. In terms of writing, we can see that the c ++ iterator looks like a pointer and a pointer that can perform auto-increment operations. C # each item obtained by iteration is the data currently stored. There are five types of iterators in the Iterator STL: Input Iterator, Output Iterator, and Forward Iterator) bidirectional Iterator and Random Access Iterator ). In C #, there is no corresponding iterator concept. After all, the iterator is a smart pointer, but C # does not support pointers (unsafe is another way ). The input iterator can only read one element forward at a time and only read this element once. If we copy an input iterator, and the copy input iterator and the original input iterator read one element forward, they may traverse different values. Use istream_iterator as the column and the code is as follows: # include <iostream> # include <vector> # include <list> # include <map> # include <set> # include <algorithm> # include <iterator> # include <string> using namespace std; int main () {// press Ctrl + Z to end the input, or press Ctrl + C to cancel the input of istream_iterator <string> iterBegin (cin); istream_iterator <string> iterEnd; while (iterBegin! = IterEnd) {cout <* iterBegin <endl; ++ iterBegin;} the output iterator is opposite to the input iterator. It is used to write element values one by one, therefore, it can only be used as the left value. The Code is as follows: # include <iostream> # include <vector> # include <list> # include <map> # include <set> # include <algorithm> # include <iterator> # include <string> using namespace std; int main () {ostream_iterator <int> iter (cout, "\ n"); vector <int> vec; for (int I = 0; I <10; ++ I) {* iter = I ;}} the forward iterator is a combination of input and input iterators, but it fails to use all the functions of the input and input iterators, I really think this iterator is embarrassing. When the forward iterator extracts a value, make sure it is an effective iterator (such as at the end of the sequence), but the output iterator does not (the output iterator does not provide a comparison operation, you do not need to check whether the end is reached ). I have never seen a representative forward iterator, so I cannot provide a sample code (pipeline ...). The bidirectional iterator adds the ability to traverse back based on the previous iterator. In terms of writing, the auto-subtraction operation is provided. The most suitable non-linked list iterator does not belong to the column. As follows: # include <map> # include <set> # include <algorithm> # include <iterator> # include <string> using namespace std; int main () {list <int> lst; for (int I = 0; I <10; ++ I) {lst. push_back (I);} list <int>: const_iterator iter (lst. begin (); while (iter! = Lst. end () {cout <* iter <""; ++ iter;} cout <endl; while (iter! = Lst. begin () {-- iter; cout <* iter <"" ;}}: the random iterator adds random access capability based on the bidirectional iterator. In terms of writing, the addition and subtraction operations are provided, and the size comparison operation is also provided (except for this iterator, there is no size comparison for others, so it is generally used to determine whether the iterator ends or not, yes = or! = ). The most suitable column is the vector iterator. Vector <int> vec; for (int I = 0; I <10; ++ I) {vec. push_back (I);} vector <int>: const_iterator iter (vec. begin (); cout <* (iter + 4) <endl; so far, we have some basic knowledge about the C ++ iterator. Now let's explore how this is implemented. We know that the STL of C ++ is implemented by Template. The C # word is used to describe the Generic type (Generic ). An iterator is actually a type that follows a series of hidden rules. Based on the degree of potential, there are two types: Self-entertainment, and the wolf is a rape. If you just want to entertain yourself, it's very easy, as long as you can: # include <iostream> # include <vector> # include <list> # include <map> # include <set> # include <algorithm> # include <iterator> # include <string> using namespace std; template <typename Item> struct ListIter; template <typename T> struct ListItem; // template <typename T> struct ListContainer {ListContainer (): _ front (nullptr), _ end (nullptr), _ size (0) {} void insert_front (T Value) {ListItem <T> * newItem = new ListItem <T> (value, _ front); if (_ front = nullptr) {_ end = newItem ;} _ front = newItem;} void insert_end (T value) {ListItem <T> * newItem = new ListItem <T> (value, nullptr); if (_ end = nullptr) {_ front = newItem; _ end = newItem;} else {_ end-> setNext (newItem); _ end = newItem ;}} void display (std :: ostream & OS = std: cout) const {ListItem <T> * tmp = _ front; wh Ile (tmp! = Nullptr) {OS <tmp-> value () <""; tmp = tmp-> next () ;} OS <std: endl ;} listItem <T> * front () const {return _ front;} private: ListItem <T> * _ end; ListItem <T> * _ front; long _ size ;}; // each element template <typename T> struct ListItem {ListItem (T val, ListItem <T> * next): _ value (val), _ next (next) {} T value () const {return _ value;} ListItem * next () const {return _ next;} void setNext (ListItem <T> * Next) {_ next = next;} private: T _ value; ListItem <T> * _ next ;}; // iterator template <typename Item> struct ListIter {Item * ptr; ListIter (Item * p = 0): ptr (p) {} Item & operator *() const {return * ptr;} Item * operator-> () const {return ptr;} ListIter & operator ++ () {ptr = ptr-> next (); return * this;} ListIter operator ++ (int) {ListIter tmp = * this; ++ (* this); return tmp;} bool operator = (const ListIter & I) const {return ptr = I. ptr;} bool operator! = (Const ListIter & I) const {return ptr! = I. ptr ;}}; int main () {ListContainer <int> myList; for (int I = 0; I <10; ++ I) {myList. insert_front (I); myList. insert_end (I + 10);} myList. display (); ListIter <ListItem <int> begin (myList. front (); ListIter <ListItem <int> end; while (begin! = End) {cout <begin-> value () <endl; ++ begin ;}} in the above Code, we fully rely on our own hands, by reloading *,->, ++, = ,! = Operator to implement an iterator similar to the iterator in its own behavior. But we can only entertain ourselves and cannot integrate into the STL family. We can't reuse the original STL wheel, nor can we perfectly put our wheel into STL (Just reload the global one! = Operator, you can use STL's find ). To implement this iterator, we expose the element type (ListItem) of the container, and expose the internal implementation details of ListItem (overload ++ operator, ptr-> next () is used, which is obviously unscientific! Generally, the iterator is implemented by the container designer and embedded in the container.

Related Article

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.