Application of the "Java" list interface compared to vector applications in C + + (i)

Source: Internet
Author: User

"Reasons for writing"

When solving the "leetcode.113 Path Sum II", I used Java and C + + respectively, feeling that the difference there is a need to tidy up a bit.

"Creation of dynamic arrays"

In programming, in many cases, during the pre-compilation process, the length of the array is not known in advance, it must be given dynamically when the program is run, but the problem is that when the programming language C + +, Java requires the definition of an array, the size of the given array must be clearly specified, or the compilation will not pass. Shape as LeetCode113 problem, to meet the requirements of the two-fork tree path, because of the diversity of the binary tree structure, a large traversal path, in advance can not determine the length of the path. At this point, we need to create a capacity that can vary the array (or memory) according to the actual needs.

[a] in C + +, the most common method is to create a dynamic array using the new method and a vector container to create variable-length arrays .

1. New method: int *p=new int[num]; Create an array of type int with num capacity, NUM can come from external input, function pass, etc., int pointer p points to the first address of the dynamic array, after the dynamic array is created, we can subscript access to the array elements: p[0],p[ 1] ..., but the new method cannot create a two-dimensional array, only one-dimensional arrays can be created, and the operation of the data elements after creation is inflexible; the most used place is the creation of a linked list node;

2, vector container: Compared to the new method, the vector container is very powerful, with a high degree of flexibility, commonly used basic operations:       

(1) header file #include<vector>.

(2) Creating one-dimensional vector object,vector<int> vec; two-dimensional vector<vector<int>> vec2;

(3) Insert number at tail: vec.push_back (a);

(4) The tail element pops up: Vec.pop_back (); the equivalent of deleting the trailing element;

(5) Use subscript to access the element,cout<<vec[0]<<endl; remember that the subscript starts at 0, and the array is accessed in the same way.

(6) Insert element: Vec.insert (Vec.begin () +i,a); Insert a in front of the first I+1 element;

(7) Delete element: Vec.erase (Vec.begin () +2); Delete 3rd element

Vec.erase (Vec.begin () +i,vec.end () +j); Delete interval [i,j-1]; interval starting from 0

(8) Vector size: vec.size ();

(9) Empty: Vec.clear ();

(10) Initialization assignment:
Vector C1 (c2)//Copy a vector (C2 is also a vector)
Vector c (n)//create a vector containing n data, the data is constructed by default
Vector c (n, elem)//create a vector containing n elem elements
Vector C (beg,end)//int array[]={1,2,3},beg=array,end=array+3, with array for vector assignment

Since we can dynamically change the data in the vector through the two functions of push_back () and Pop_back (), it is very easy to make dynamic storage space by vector, which is widely used in C + +.

3. Common algorithms

1) Flip the element with reverse: Requires a header file #include<algorithm>

Reverse (Vec.begin (), Vec.end ()); Flips the element (in the vector, if two iterators are required in a function, the latter does not usually contain.)

2) Sorting using Sort: Requires header file #include<algorithm>

Sort (Vec.begin (), Vec.end ());(by default in ascending order, that is, from small to large).

You can compare functions in descending order by overriding the sort comparison, as follows:

To define a sort comparison function:

BOOL Comp (int a,int b)
{
Return a>b;
}
Called When: Sort (Vec.begin (), Vec.end (), Comp), so that it is sorted in descending order.


[II] in Java, the most common way is: using the ArrayList and list interface

The Java collection is divided into three main types:
Set (SET)
List (lists)
Map (map)
To understand the collection in depth first understand the familiar array: the array is fixed in size, and the same array can hold only the same type of data (base type/reference type), while the Java collection stores and operates a set of data that is not fixed. All Java collections are located in the Java.util package! In Java, there is an array class, specifically for manipulating arrays, it is useful, but it can not implement the capacity of the array dynamic increase or decrease, so, to use the collection, the collection has a lot of advantages, this problem can be written in a separate article, here is not detailed!!!

1, Arraylist:java dynamic array is a kind of object that can arbitrarily stretch the length of the array, in Java is more commonly used is ArrayList create dynamic array, simple example:

ArrayList temp = new ArrayList (); Create a ArrayList object, temp for the object's reference for (int i=0;i <10;i++)//Add 10 int element temp to the array. ADD (i); Temp. RemoveAt (5);//Remove the 6th element for the for (int i=0;i<3;i++)//Add 3 element Temp. ADD (I+20); Int32[] values = (int32[]) temp. ToArray (typeof (Int32));//Returns the ArrayList contained array
1) ArrayList is a complex version of array
ArrayList internally encapsulates an array of type Object, which, in general terms, has no intrinsic difference, and even ArrayList many methods, such as index, INDEXOF, Contains, Sort is the corresponding method of calling array directly on the basis of an internal array.
2) The effect of the internal object type
For general reference types, this part of the impact is not very large, but for value types, adding and modifying elements inside the ArrayList will result in boxing and unpacking operations, and frequent operations may affect some of the efficiency. But for most people, most applications use arrays of value types.
There is no way to eliminate this effect, unless you do not use it, you will have to take part of the efficiency loss, but this part of the loss will not be very large.
3) Array expansion
This is a factor that has a great influence on the efficiency of ArrayList.
Whenever a method of adding elements, such as Add, AddRange, Insert, Insertrange, is checked, the capacity of the internal array is not sufficient, and if it is, it will reconstruct an array at twice times the current capacity, copy the old elements into the new array, and discard the old array. At this point in the expansion operation, it should be compared to the impact of efficiency.

2. The list interface in Java:

We know that in Java, interfaces are not classes and cannot be instantiated using the new method, but interfaces can declare interface variables such as list temp, and interface variables must refer to objects that implement the interface's class, such as the ArrayList class implements the List interface, then:list< String> temp=new arraylist<string> () is legal.

A list is characterized by its elements being stored in a linear fashion, in which duplicate objects can be stored in the collection. The main implementation classes of the list interface are:
(1) ArrayList (): The length of the representation can be changed by the group. Elements can be randomly accessed, and it is slow to insert and delete elements into ArrayList ().
(2) LinkedList (): A linked list data structure is used in the implementation. Fast insertion and deletion, and slow access times.

The list interface is commonly used in the following ways:

using the methods provided by the list interface above, we can do a "rich" operation on the data in the list, following an example to understand the application of the list interface: "Leetcode" 113. Path Sum II Solution:

/** * Definition for a binary tree node.  * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution {public list<list<integer>> pathsum (TreeNode root, int sum) {list<l Ist<integer>> result=new arraylist<list<integer>> ();//list interface references ArrayList class objects List<integer   > Temp=new arraylist<integer> ();//list reference ArrayList object, holding the current path if (root==null) return result;   DFS (result,temp,root,sum);    return result; } void DFS (list<list<integer>> result,list<integer> temp,treenode root,int sum) {if (root==n   ULL) return; if (root.left==null&&root.right==null) {temp.add (root.val);//add element in current path if (Sumofpath (temp) ==sum) Result.add   (New ArrayList (temp));//Note the use of the Add () method of the list interface Temp.remove (Temp.size ()-1);//The current path end element pops up, note that the subscript starts at 0 return; } else {temp.add (root.val);//current path add element, with Add () DFS (result,temp,root.left,sum);   DFS (result,temp,root.right,sum);   Temp.remove (Temp.size ()-1);//current path popup end element}} int Sumofpath (list<integer> temp) {int sum=0;   for (int i=0;i<temp.size (); i++) {sum+=temp.get (i);//Use the Get () method to get the element labeled I} return sum; }}

Follow-up replenishment ...



Read article: http://blog.csdn.net/speedme/article/details/22398395





Application of the "Java" list interface compared to vector applications in C + + (i)

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.