Home > Articles > Programming > C/C++

This chapter is from the book

Containers

Arrays have several disadvantages. Earlier in this chapter we discussed their lack of size information, which means you must use two arguments to pass an array to a function. It also means that you cannot check an array index at runtime to see whether it's out of bounds. It is easy to crash a program by using the wrong index; what is perhaps worse—because the program seems to work—is that memory can be silently overwritten. All C programmers will tell you that these are some of the worst bugs to solve. Built-in arrays are also inflexible in that they have a fixed size that must be a constant. Although it is very fast to access array data randomly, insertions and deletions are slow.

The standard library defines a number of container types. A container holds a number of elements, like an array, but it is more intelligent. In particular, it has size information and is resizable. We will discuss three kinds of standard containers in the following sections: vector, which is used like a built-in array, but is resizeable; list, which is easy to insert elements into; and map, which is an associative array. That is, it associates values of one type with another type.

Resizable Arrays: std::vector

You use the vector container type the same way you use an ordinary array, but a vector can grow when required. The following is a vector of 10 ints:

;> vector<int> vi(10);
;> for(int i = 0; i < 10; i++) vi[i] = i+1;
;> vi[5];
(int&) 6
;> vector<int> v2;
;> v2.size();
(int) 0
;> v2 = vi;
;> v2.size();
(int) 10

vector is called a parameterized type. The type in angle brackets (<>) that must follow the name is called the type parameter. vector is called parameterized because each specific type (vector<int>, vector<double>, vector<string>, and so on) is built on a specific base type, like a built-in array. In Chapter 10, "Templates," I will show you how you can build your own parameterized types, but for now it's only important that you know how to use them.

vi is a perfectly ordinary object that behaves like an array. That is, you can access any element very quickly using an index; this is called random access. Please note that the initial size (what we would call the array dimension) is in parentheses, not in square brackets. If there is no size (as with v2) then the vector is initially of size zero. It keeps its own size information, which you can access by using the size() method. You cannot initialize a vector in the same way as an array (with a list of numbers), but you can assign them to each other. The statement v2 = vi actually causes all the elements of vi to be copied into v2. A vector variable behaves just like an ordinary variable, in fact. You can pass the vi vector as an argument to a function, and you won't need to pass the size, as in the following example:

void show_vect(vector<int> v)
{ 
  for(int i = 0; i < v.size(); i++) cout << v[i] << ` `; 
  cout << endl;
}
;> show_vect(vi);
1 2 3 4 5 6 7 8 9 10

You can resize the vector vi at any point. In the following example the elements of vi are initialized to random numbers between 0 and 99. (n % 100 will always be in that range). vi is then resized to 15 elements:

;> for(int i = 0; i < 10; i++) vi[i] = rand() % 100;
;> show_vect(vi);
41 67 34 0 69 24 78 58 62 64
;> vi.resize(15);
show_vect(vi);
41 67 34 0 69 24 78 58 62 64 0 0 0 0 0

You can resize the vi vector without destroying its values, but this can sometimes be quite a costly operation because the old values must be copied. Note that vectors are passed to functions by value, not by reference. Remember that passing by value involves making a copy of the whole object. In the following example, the function try_change() tries to modify its argument, but doesn't succeed. Earlier in this chapter ("Passing Arrays to Functions") you saw a similar example with built-in arrays, which did modify the first element of its array argument.

;> vector<int> v2 = vi;
;> v2.size();
(int) 15
;> v2[0];
(int&) 41
;> void try_change(vector<int> v) { v[0] = 747; }
;> try_change(v2);
;> v2[0];
(int&) 41

At this point, you may be tired of typing vector<int>. Fortunately, C++ provides a shortcut. You can create an alias for a type by using the typedef statement. The form of the typedef statement is just like the form of a declaration, except the declared names are not variables but type aliases. You can use these typedef names wherever you would have used the original type. Here are some examples of how to use typedef, showing how the resulting aliases can be used instead of the full type:

;> typedef unsigned int uint;
;> typedef unsigned char uchar;
;> typedef vector<int> VI;
;> typedef vector<double> DV;
;> uint arr[10]; 
;> DV d1(10),d2(10);
;> VI v1,v2;
;> int get(VI v, int i) { return v[i]; }

Think of typedef names as the equivalent of constants. Symbolic constants make typing easier (typing pi to 12 decimal places each time is tedious) and make later changes easier because there is only one statement to be changed. In the same way, if I consistently use VI throughout a large program, then the code becomes easier to type (and to read). If I later decide to use some other type instead of vector<int>, then that changes becomes straightforward.

As you have learned, passing a vector (or any standard container) to a function involves a full copy of that vector. This can make a noticeable difference to a program's performance if the function is called enough times. You can mark an argument so that it is passed by reference, by using the address operator (&). You can further insist that it remains constant, as we did earlier in the chapter for arrays and as shown in the following example:

void by_reference (vector<int>& vi)
 { vi[0] = 0; }
void no_modify (const vector<int>& vi)
 { cout << vi[0] << endl; }

Generally, you should pass vectors and other containers by reference; if you need to make a copy, it's best to do it explicitly in the function and make such reference arguments const, unless you are going to modify the vector. When experienced programmers see something passed by reference, they assume that someone is going to try to change it. So the preferred way of passing containers is by const reference, as in the preceding example. You can always use the typedef names to make things look easier on the eye, as shown here:

int passing_a_vector (const VI& vi) { return vi[0]; }

The standard string is very much like a vector<char>, and it is considered an "almost container." Strings can also be indexed like arrays, so if s is a string, then s[0] would be the first character (not substring), and s[s.size()-1] would be the last character.

Linked Lists: std::list

vectors have strengths and weaknesses. As you have seen, any insertion requires moving elements, so if a vector contained several million elements (and why not?), insertion could be unacceptably slow. Although vectors grow automatically, that process can also be slow because it involves copying all the elements in the vector.

Lists are also sequences of elements, but they are not accessed randomly, and they are therefore not like arrays. Starting with an empty list, you append values by using push_back(), and you insert values at the front of the list by using push_front(). back() and front() give the current values at each end. To remove values from the ends, you use pop_front() and pop_back(). The following is an example of creating a list:

;> list<int> li;
;> li.push_back(10);
;> li.push_front(20);
;> li.back();
(int) 10
;> li.front();
(int) 20
;> li.size();
(int) 2
;> li.pop_back();
;> li.back();
(int) 20

You can remove from a list all items with a certain value. After the remove operation, the list contains only "two":

;> list<string> ls;
;> ls.push_back("one"); ls.push_back("two"); ls.push_back("one");
;> ls.remove("one");

Associative Arrays: std::map

In mathematics, a map takes members of some input set (say 0..n-1) to another set of values; a simple example would be an array. The standard C++ map is not restricted to contiguous (that is, consecutive) values like an array or a vector, however. Here is a simple map from int to int:

;> map<int,int> mii;
;> mii[4] = 2;
(int&) 2;
;> mii[88] = 7;
(int&) 7
;> mii.size();
(int) 2
;> mii[4];
(int&) 2
;> mii[2];
(int&) 0

You access maps the same way you access arrays, but the key values used in the subscripting don't have to cover the full range. To create the map in the preceding example by using arrays, you would need at least 89 elements in the array, whereas the map needs only 2. If you consider a map of phone numbers and contact names, you can see that an ordinary array is not an option. maps become very interesting when the key values are non-integers; we say that they associate strings with values, and hence they are often called associative arrays. Typically, a map is about as fast as a binary search.

;> map<int,string> mis;
;> mis[6554321] = "James";
(string&) "James";
;> mis.size();
(int) 1
;> map<string,int> msi;
;> msi["James"] = 6554321;
(int&) 6554321
;> msi.size();
(int) 1
;> msi["Jane"];
(int&) 0
;> msi.size();
(int) 2

Something that is important to note about maps is that they get bigger if you are continuously querying them with different keys. Say you are reading in a large body of text, looking for a few words. If you are using array notation, each time you look up a value in the map, the map gets another entry. So a map of a few entries can end up with thousands of entries, most of which are trivial. Fortunately, there is a straightforward way around this: You can use the map's find() method. First, you can define some typedef names to simplify things:

;> typedef map<string,int> MSI;
;> typedef MSI::iterator IMSI;
;> IMSI ii = msi.find("Fred");
;> ii == msi.end();
(bool) true

The find() method returns a map iterator, which either refers to an existing item or is equal to the end of the map.

Maps are some of the most entertaining goodies in the standard library. They are useful tools, and you can use them to write very powerful routines in just a few lines. Here is a function that counts word frequencies in a large body of text (testing this case, the first chapter of Conan Doyle's Hound of the Baskervilles, courtesy of the Gutenberg Project):

int word_freq(string file, MSI& msi) {
   ifstream in(file.c_str());
   string word;
   while (in >> word) msi[word]++;
   return msi.size();
}
;> word_freq("chap1.txt",msi);
(int) 945
;> msi["the"];
(int&) 94

This example uses the shorthand for opening a file, and it assumes that the file will always exist. The real fun happens on the fourth line in this example. For each word in the file, you increment the map's value. If a word is not originally present in the map, msi[word] is zero, and a new entry is created. Otherwise, the existing value is incremented. Eventually, msi will contain all unique words, along with the number of times they have been used. This example is the first bit of code in this book that really exercises a machine. The UnderC implementation is too slow for analyzing large amounts of text, but Chapter 4, "Programs and Libraries," shows how to set up a C++ program that can be compiled into an executable program.

Stacks and Queues

Sometimes it's useful to build up a vector element by element. This works exactly like adding to the end of a list. You can add new elements at the end with push_back(); back() gives the value of the last value of the vector, and pop_back() removes the last value, decrementing the size.

;> typedef vector<int> VI;
;> VI vs;
;> vs.push_back(10);
;> vs.push_back(20);
;> show_vect(vs);
10 20
;> vs.size();
(int) 2
;> vs.back();
(int) 20
;> vs.pop_back();
;> vs.back();
(int) 10
;> vs.size();
(int) 1

void read_some_numbers(VI& vi, string file) {
  int val;
  ifstream in(file.c_str());
  while (in >> val)  vi.push_back(val);
}

Often you are given input without any idea of how many numbers to expect. If you use push_back(),the vector automatically increases in size to accommodate the new numbers. So the function read_some_numbers() will read an arbitrary number of integers and add them to the end of the vector.

There is no push_front() method because that would potentially be an expensive operation. If you really need to do it, you can use vi.insert(vi.begin(),val).

The operations push and pop define a stack. A stack is similar to the spring-loaded device often used for dispensing plates in cafeterias. As you remove plates from the top of the device (that is, "pop the stack"), more plates rise and are ready to be taken. You can also push plates onto the pile. A stack operates in first-in, last-out (FILO) fashion: if you push 10, 20, and 30, then you will pop 30, 20, and 10. Stacks are one of the basic workhorses of computer science, and you see them all over the place. A common use is to save a value, as in the following example:

void push(int val) {
  vi.push_back(val);
}
int  pop() {
  int val = vi.back();
  vi.pop_back();
  return val;
}
;> int val = 1;
;> push(val);     // save val;
;> val = 42;      // modify val;
(int) 42
.... do things with val.......
;> val = pop();   // restore val;

A queue, on the other hand, operates in first-in, first-out (FIFO) fashion, similarly to a line of waiting people, who are served in first come, first served order. A vector is not a good implementation of a queue because inserting at the front causes all entries to shuffle along. lists, however, are good candidates for queuing. You add an item to a queue by using push_front(), and you take an item off the end by using pop_back(). Queues are commonly used in data communications, where you can have data coming in faster than it can be processed. So incoming data is buffered—that is, kept in a queue until it is used or the buffer overflows. The good thing about a list is that it never overflows, although it can underflow, when someone tries to take something off an empty queue; therefore, it is important to check size. Graphical user interface systems such as Windows typically maintain a message queue, which contains all the user's input. So it is possible to type faster than a program can process keystrokes.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020