Vector Container objects in C + + learning notes _c language

Source: Internet
Author: User
Tags class definition function definition in python

The arrays in C + + are very pits, are there any data types like the list in Python? It's like vector!. A vector is a collection of objects of the same type, each of which has a corresponding integer index value. As with a string object, the standard library is responsible for managing the memory associated with the storage element. We refer to the vector as a container because it can contain other objects. All objects in a container must be of the same type.

Definition and initialization of vector objects

Similarly, before using, import header file #include <vector> can use using declaration: using Std::vector;

Vector is a class template (class template). You can use a template to write a class definition or function definition, and for multiple different data types. Therefore, we can define vectors that hold the vector of a string object, or a vector that holds an int value, or a vector that holds a custom class type object, such as a Sales_items object.

Declaring a type of object generated from a class template requires additional information, and the type of information depends on the template. Vector, for example, must describe the type of object the vector holds, specifying the type by placing the type in angle brackets after the class template name:

Vector<t> v1; The save type is a T object. The default constructor v1 is empty.
Vector<t> v2 (v1); V2 is a copy of v1.
Vector<t> v3 (n, i); V3 contains an element with n values of I.
Vector<t> v4 (n); V4 n copies of elements that contain value initialization.

"Note: 1, to create a non-empty vector object, you must give the value of the initialization element; 2, when a vector object is copied to another vector object, each element in the newly copied vector is initialized to a copy of the corresponding element in the original vectors. However, the two vector objects must hold the same element type, 3, the vector object can be initialized with the number of elements and element values. The constructor uses the number of elements to determine which vector object holds the element.

Number, the element value specifies the initial value of each element.

Vector objects Grow dynamically:

The important property of a vector object (and other standard library container objects) is that you can efficiently add elements at run time.

"Note: because

Vector growth efficiency is high

, it is best to add elements dynamically when element values are known. 】
Value initialization:

If the initialization of the element is not specified, then the standard library will provide itself with an element initializer, depending on the data type of the element stored in the vector.

If int data, then the standard library will create an element initializer with a value of 0;

If the vector holds elements of a class type (such as a string) that contains constructors, the standard library creates an element initializer with the default constructor of that type;

The element type may be a class type that does not have any constructors defined. In this case, the standard library still produces an object with an initial value, and each member of the object is initialized with a value.

#include <iostream>
#include <string>
#include <vector>

int main ()
{
 std:: Vector<int> A;
 Std::vector<int> B (a);
 Std::vector<int> C (a);
 std::vector<std::string> Svec ("null");
 Std::vector<std::string> svec2 ("hi!");
 Std::vector<std::string> SVEC3 (a);
 return 0;
}

Note that there is no = number!
Vector Object Manipulation method

Similar to String!
. V.empty ()

Returns true if V is empty; Otherwise returns False if V is empty, returns True, otherwise returns false.

. V.size ()

Returns number of elements in V returns the count of elements in V.

"NOTE: 1, returns the value of the size_type defined by the corresponding vector class, similar to string. 2. When using the Size_type type, you must indicate where the type is defined. Vector types always include always

The element type that includes vector vector<int>::size_type

V.push_back (t)

Adds element with the value T to end of V adds a value of T to the ends of V. The following are examples:

#include <iostream>
#include <string>
#include <cctype>
#include < vector>

int main ()
{
 //read words from the standard input and store them as elements in a vector
 std:: string Word;
 std::vector<std::string> text; Empty vector while
 (std::cin >> Word) 
 {
 text.push_back (word);//append Word to text for
 ( Std::vector<int>::size_type IX = 0; IX!= text.size (); ++ix)
  std::cout<< "Now text[" <<ix<< "]is:" <<text[ix]<<std::endl;
 }
 return 0;
}

The results are:

Hello now
Text[0]is:hello
world!
Now Text[0]is:hello now
text[1]is:world!


Attention:
1, can not directly output vector objects! And the list is too different ...

2, subscript operation can change the existing elements: for example, the last example can be added at the end: text[0] = "elements";

3, of course, and the same as the list, certainly can not text[100] = "elements"; in Python this operation list returns subscript out of bounds, C + + compiler will not complain, run automatic exit! "Array operation this will pit you, will not complain, will not quit!" Of course, the buffer overflow, hackers are too fond of! 】

4, due to dynamic growth, can not test the length of the first, but the dynamic test cycle! Otherwise, there will be bug!. Some people are worried about efficiency? Don't worry! The cost is very small "inline function".

V[n]

Returns element at position N in v returns elements in V with position N.

(1) v1 = V2[/code]

Replaces elements in V1 by a copy of the elements in V2 replaces the elements of the V1 with a copy of the elements in the V2.

(2) V1 = = V2[/code]

Returns true if V1 and V2 are equal returns True if V1 is equal to V2.

(3)!=, <=,>, and >=

Have their normal meanings maintain the usual meaning of these operators.

A simple example

Reads a piece of text into a vector object, and each word is stored as an element in the vector. Converts each word in the vector object to uppercase. Outputs the transformed elements in a vector object, one row for each eight words.

Suppose the text is: in the vector. Transform each word into uppercase letters. Print the transformed elements from the vector, printing eight words to a line.

#include <iostream>
#include <string>
#include <vector>

std::string deal_word (std:: String word)
{
 std::string Word;//Create an empty string for
 (std::string::size_type IX =0 IX!= word.size (); ++ix)
 { C8/>if (not ispunct (Word[ix]))
 {
  Word + = ToUpper (Word[ix]);//Connect non-punctuation characters to string
 } return
 word;

int main ()
{
 std::string Word;//cache input Word
 std::vector<std::string> text;//empty vector
 std::cout<< " Please input the text: "<<std::endl; Tip Enter
 while (std::cin >> word and Word!= "inputover")//Inputover to mark the end of the input, or CTRL + Z to stop typing 
 {
 word = Deal_word (Word);  word processing
 text.push_back (word);//append Word to Text
 }
 for (Std::vector<int>::size_type ix =0, j = 0; IX!= text.size (); ++ix, ++j)
 {
 if (j==8)//8 Word line
 {
  std::cout<<std::endl;//newline
  j = 0;//re-count
 }
  std::cout<<text[ix]<< ""; Add space!
 }
 return 0;
}

The results are:

Please input the "text: in"
vector. Transform each word into uppercase letters. Print the transformed elements from the vector, printing eight words to a line. Inputover in the
VECTOR TRANSFORM all WORD into uppercase 
letters PRINT the transformed ELEMENTS from the vector< C4/>printing eight WORDS to A line

Vector.resize and Vector.reserve

The reserve is a container reservation, but does not really create an element object and cannot refer to elements within the container until the object is created, so when you add a new element, you need to use the push_back ()/insert () function.
Resize is to change the size of the container and create the object, so after calling the function, you can refer to the object within the container, so when you add the new element, use the operator[operator, or use an iterator to refer to the element object.
Furthermore, two functions in the form of a difference, the reserve function after a parameter, that is required to reserve the space of the container; The resize function can have two parameters, the first parameter is the new size of the container, and the second parameter is the new element to be added to the container, if the argument is omitted, Then the default constructor for the element object is invoked. The following are examples of the use of these two functions:

Vector<int> Myvec;

Myvec.reserve (m);  The new element is not yet constructed,

       //cannot be accessed at this time with [] access element for

(int i = 0; i < i++)

... {

  myvec.push_back (i);//new element then constructs

}

myvec.resize (102);  Two new elements are constructed with the default constructor of the element

myvec[100] = 1;   Direct manipulation of the new element

myvec[101] = 2;

The first contact between the two interfaces may be confusing, in fact, the interface of the name is a perfect description of the function, resize is to redistribute size, reserve is to reserve a certain space. There are differences and similarities between the two interfaces. The following is an analysis of their details.
To implement the semantics of resize, the resize interface makes two guarantees:
One is to ensure that the interval [0, new_size) range of data is valid, if subscript index within this interval, Vector[indext] is legal.
Second, the guarantee interval [0, new_size) outside the scope of the data is invalid, if subscript index in the interval, Vector[indext] is illegal.
Reserve simply guarantees that the vector's space size (capacity) reaches at least the size n specified by its parameters. Within the range [0, n], if the subscript is index,vector[index] Such access may be lawful and may be unlawful, depending on the circumstances.
What the resize and the reserve interfaces have in common is that they ensure that the vector's space size (capacity) reaches at least the size specified by its parameters.
Because the source code for both interfaces is so streamlined that it can be posted here:

void Resize (size_type new_size) 
{ 
 resize (new_size, T ()); 
}
void Resize (size_type new_size, const t& x) 
{
 if (New_size < size ()) 
  Erase (Begin () + new_size, End ()); Erase data outside the range to ensure that the data outside the interval is not valid
 else
  insert (end (), New_size-size (), x);//Fill the gaps in the range and make sure the data in the interval is valid
} 

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.