📜  数组和映射的区别

📅  最后修改于: 2021-09-03 04:15:53             🧑  作者: Mango

大批:

数组是存储在连续内存位置的项目的集合。这个想法是将多个相同类型的项目存储在一起。这使得通过简单地将偏移量添加到基值,即数组的第一个元素的内存位置(通常由数组的名称表示)来更容易地计算每个元素的位置。
数组的图示如下:

方案一:
下面是一维数组的图示:

C++14
// C++ program to illustrate 1D array
#include 
using namespace std;
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 6, 10, 5, 0 };
 
    // Print the array elements
    for (int i = 0; i < 4; i++) {
        cout << arr[i] << " ";
    }
 
    return 0;
}


Java
// Java program to illustrate 1D array
class GFG{
 
// Driver Code
public static void main(String[] args)
{
    // Given array
    int arr[] = { 6, 10, 5, 0 };
 
    // Print the array elements
    for (int i = 0; i < 4; i++)
    {
        System.out.print(arr[i] + " ");
    }
}
}
 
// This code is contributed by Rohit_ranjan


Python3
# Python3 program to illustrate 1D array
 
# Driver Code
if __name__ == '__main__':
   
    # Given array
    arr = [6, 10, 5, 0];
 
    # Prthe array elements
    for i in range(0, 4):
        print(arr[i], end = " ");
 
# This code is contributed by Rohit_ranjan


C#
// C# program to illustrate 1D array
using System;
class GFG{
 
    // Driver Code
    public static void Main(String[] args)
    {
 
        // Given array
        int[] arr = {6, 10, 5, 0};
 
        // Print the array elements
        for (int i = 0; i < 4; i++)
        {
            Console.Write(arr[i] + " ");
        }
    }
}
 
// This code is contributed by Rajput-Ji


C++14
// C++ program to illustrate 1D array
#include 
using namespace std;
 
// Driver Code
int main()
{
    // A 2D array with 3 rows and
    // 2 columns
    int x[3][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
 
    // Print each array element value
    // Traverse row
    for (int i = 0; i < 3; i++) {
 
        // Traverse column
        for (int j = 0; j < 2; j++) {
 
            // Print element
            cout << "Element at x[" << i
                 << "][" << j
                 << "]: ";
            cout << x[i][j] << endl;
        }
    }
    return 0;
}


Java
// Java program to illustrate 1D array
import java.util.*;
class GFG{
 
// Driver Code
public static void main(String[] args)
{
    // A 2D array with 3 rows and
    // 2 columns
    int x[][] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
 
    // Print each array element value
    // Traverse row
    for (int i = 0; i < 3; i++)
    {
 
        // Traverse column
        for (int j = 0; j < 2; j++)
        {
 
            // Print element
            System.out.print("Element at x[" +  i +
                             "][" +  j + "]: ");
            System.out.print(x[i][j] + "\n");
        }
    }
}
}
 
// This code is contributed by Princi Singh


Python3
# Python3 program to illustrate 1D array
 
# Driver Code
if __name__ == '__main__':
   
    # A 2D array with 3 rows and
    # 2 columns
    x = [[0, 1], [2, 3], [4, 5]];
 
    # Preach array element value
    # Traverse row
    for i in range(3):
 
        # Traverse column
        for j in range(2):
            # Prelement
            print("Element at x[" , i ,
                  "][" , j , "]: ", end = "");
            print(x[i][j]);
 
# This code is contributed by sapnasingh4991


C#
// C# program to illustrate 1D array
using System;
class GFG{
 
// Driver Code
public static void Main(String[] args)
{
    // A 2D array with 3 rows and
    // 2 columns
    int [,]x = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
 
    // Print each array element value
    // Traverse row
    for (int i = 0; i < 3; i++)
    {
 
        // Traverse column
        for (int j = 0; j < 2; j++)
        {
 
            // Print element
            Console.Write("Element at x[" +  i +
                              "," +  j + "]: ");
            Console.Write(x[i,j] + "\n");
        }
    }
}
}
 
// This code is contributed by Princi Singh


C++
// C++ program to illustrate Map
#include 
using namespace std;
 
// Driver Code
int main()
{
    // Empty map container
    map gquiz1;
 
    // Insert elements in Map
    gquiz1.insert(pair(1, 40));
    gquiz1.insert(pair(2, 30));
    gquiz1.insert(pair(3, 60));
 
    // Iterator to iterate Map
    map::iterator itr;
 
    cout << "\nThe map gquiz1 is : \n";
    cout << "\tKEY\tELEMENT\n";
 
    // Print map gquiz1
    for (itr = gquiz1.begin();
         itr != gquiz1.end(); ++itr) {
        cout << '\t' << itr->first
             << '\t' << itr->second
             << '\n';
    }
    return 0;
}


Java
// Java program to illustrate Map
import java.util.*;
class GFG{
 
// Driver Code
public static void main(String[] args)
{
    // Empty map container
    HashMap gquiz1 = new HashMap();
 
    // Insert elements in Map
    gquiz1.put(1, 40);
    gquiz1.put(2, 30);
    gquiz1.put(3, 60);
 
    // Iterator to iterate Map
    Iterator> itr = gquiz1.entrySet().
                                              iterator();
 
    System.out.print("\nThe map gquiz1 is : \n");
    System.out.print("KEY\tELEMENT\n");
 
    // Print map gquiz1
    while(itr.hasNext())
    {
        Map.Entry entry = itr.next();
        System.out.print('\t' + entry.getKey()
                         + "\t" + entry.getValue()+ "\n");
    }
}
}
 
// This code is contributed by shikhasingrajput


Python3
# Python3 program to illustrate Map
 
# Driver Code
if __name__ == '__main__':
     
    # Empty map container
    gquiz1 = dict()
 
    # Insert elements in Map
    gquiz1[1] = 40
    gquiz1[2] = 30
    gquiz1[3] = 60
 
    print("\nThe map gquiz1 is : ")
    print("KEY\tELEMENT")
 
    for x, y in gquiz1.items():
        print(x, "\t", y)
 
# This code is contributed by Rajput-Ji


C#
// C# program to illustrate Map
using System;
using System.Collections.Generic;
 
class GFG{
 
// Driver Code
public static void Main(String[] args)
{
     
    // Empty map container
    Dictionary gquiz1 = new Dictionary();
                                             
    // Insert elements in Map
    gquiz1.Add(1, 40);
    gquiz1.Add(2, 30);
    gquiz1.Add(3, 60);
     
    Console.Write("\nThe map gquiz1 is : \n");
    Console.Write("\tKEY\tELEMENT\n");
     
    // Print map gquiz1
    foreach(KeyValuePair entry in gquiz1)
    {
        Console.Write("\t" + entry.Key +
                      "\t" + entry.Value + "\n");
    }
}
}
 
// This code is contributed by Amit Katiyar


C++14
// C++ program to illustrate Map
#include 
using namespace std;
 
// Driver Code
int main()
{
    // Declaring umap of 
    // type key will be of string and
    // mapped value will be of doubl
    unordered_map umap;
 
    // Insert values by using [] operator
    umap["GeeksforGeeks"] = 10;
    umap["Practice"] = 20;
    umap["Contribute"] = 30;
 
    // Traversing an unordered map
    // and print the key-value pairs
    for (auto x : umap)
        cout << x.first << " "
             << x.second << endl;
    return 0;
}


Java
// Java program to illustrate Map
import java.util.*;
 
class GFG{
 
// Driver Code
public static void main(String[] args)
{
     
    // Declaring umap of 
    // type key will be of String and
    // mapped value will be of doubl
    HashMap umap = new HashMap<>();
 
    // Insert values by using [] operator
    umap.put("GeeksforGeeks", 10);
    umap.put("Practice", 20);
    umap.put("Contribute", 30);
 
    // Traversing an unordered map
    // and print the key-value pairs
    for(Map.Entry x : umap.entrySet())
        System.out.print(x.getKey() + " " +
                         x.getValue() + "\n");
}
}
 
// This code is contributed by amal kumar choubey


C#
// C# program to illustrate Map
using System;
using System.Collections.Generic;
class GFG{
 
    // Driver Code
    public static void Main(String[] args)
    {
 
        // Declaring umap of 
        // type key will be of String and
        // mapped value will be of doubl
        Dictionary umap = new Dictionary();
 
        // Insert values by using [] operator
          umap.Add("Contribute", 30);
        umap.Add("GeeksforGeeks", 10);
        umap.Add("Practice", 20);       
 
        // Traversing an unordered map
        // and print the key-value pairs
        foreach(KeyValuePair x in umap)
            Console.Write(x.Key + " " + x.Value + "\n");
    }
}
 
// This code is contributed by Rajput-Ji


C++14
// C++ program to illustrate Multimap
#include 
using namespace std;
 
// Driver Code
int main()
{
    // Empty multimap container
    multimap gquiz1;
 
    // Insert elements
    gquiz1.insert(pair(1, 40));
    gquiz1.insert(pair(2, 30));
 
    // Iterator
    multimap::iterator itr;
 
    cout << "\nThe multimap gquiz1 is : \n";
    cout << "\tKEY\tELEMENT\n";
 
    // Print multimap gquiz1
    for (itr = gquiz1.begin();
         itr != gquiz1.end(); ++itr) {
 
        cout << '\t' << itr->first
             << '\t' << itr->second
             << '\n';
    }
    return 0;
}


C++14
// C++ program to illustrate
// unordered multimap
#include 
using namespace std;
 
// Driver Code
int main()
{
    // Empty initialization
    unordered_multimap umm1;
 
    // Initialization by intializer list
    unordered_multimap umm2(
        { { "apple", 1 },
          { "ball", 2 },
          { "apple", 10 },
          { "cat", 7 },
          { "dog", 9 },
          { "cat", 6 },
          { "apple", 1 } });
 
    // Traversing an unordered_multimap
    // and print the elements stored
    for (auto x : umm2) {
        cout << x.first << " "
             << x.second << endl;
    }
    return 0;
}


输出:
6 10 5 0

方案二:
下面是一个二维数组的说明:

C++14

// C++ program to illustrate 1D array
#include 
using namespace std;
 
// Driver Code
int main()
{
    // A 2D array with 3 rows and
    // 2 columns
    int x[3][2] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
 
    // Print each array element value
    // Traverse row
    for (int i = 0; i < 3; i++) {
 
        // Traverse column
        for (int j = 0; j < 2; j++) {
 
            // Print element
            cout << "Element at x[" << i
                 << "][" << j
                 << "]: ";
            cout << x[i][j] << endl;
        }
    }
    return 0;
}

Java

// Java program to illustrate 1D array
import java.util.*;
class GFG{
 
// Driver Code
public static void main(String[] args)
{
    // A 2D array with 3 rows and
    // 2 columns
    int x[][] = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
 
    // Print each array element value
    // Traverse row
    for (int i = 0; i < 3; i++)
    {
 
        // Traverse column
        for (int j = 0; j < 2; j++)
        {
 
            // Print element
            System.out.print("Element at x[" +  i +
                             "][" +  j + "]: ");
            System.out.print(x[i][j] + "\n");
        }
    }
}
}
 
// This code is contributed by Princi Singh

蟒蛇3

# Python3 program to illustrate 1D array
 
# Driver Code
if __name__ == '__main__':
   
    # A 2D array with 3 rows and
    # 2 columns
    x = [[0, 1], [2, 3], [4, 5]];
 
    # Preach array element value
    # Traverse row
    for i in range(3):
 
        # Traverse column
        for j in range(2):
            # Prelement
            print("Element at x[" , i ,
                  "][" , j , "]: ", end = "");
            print(x[i][j]);
 
# This code is contributed by sapnasingh4991

C#

// C# program to illustrate 1D array
using System;
class GFG{
 
// Driver Code
public static void Main(String[] args)
{
    // A 2D array with 3 rows and
    // 2 columns
    int [,]x = { { 0, 1 }, { 2, 3 }, { 4, 5 } };
 
    // Print each array element value
    // Traverse row
    for (int i = 0; i < 3; i++)
    {
 
        // Traverse column
        for (int j = 0; j < 2; j++)
        {
 
            // Print element
            Console.Write("Element at x[" +  i +
                              "," +  j + "]: ");
            Console.Write(x[i,j] + "\n");
        }
    }
}
}
 
// This code is contributed by Princi Singh
输出:
Element at x[0][0]: 0
Element at x[0][1]: 1
Element at x[1][0]: 2
Element at x[1][1]: 3
Element at x[2][0]: 4
Element at x[2][1]: 5

地图:

映射是一种关联容器,以映射方式存储元素。每个元素都有一个键值和一个映射值。没有两个映射值可以具有相同的键值。

Map的示意图如下:

方案一:
下面是一张地图的插图:

C++

// C++ program to illustrate Map
#include 
using namespace std;
 
// Driver Code
int main()
{
    // Empty map container
    map gquiz1;
 
    // Insert elements in Map
    gquiz1.insert(pair(1, 40));
    gquiz1.insert(pair(2, 30));
    gquiz1.insert(pair(3, 60));
 
    // Iterator to iterate Map
    map::iterator itr;
 
    cout << "\nThe map gquiz1 is : \n";
    cout << "\tKEY\tELEMENT\n";
 
    // Print map gquiz1
    for (itr = gquiz1.begin();
         itr != gquiz1.end(); ++itr) {
        cout << '\t' << itr->first
             << '\t' << itr->second
             << '\n';
    }
    return 0;
}

Java

// Java program to illustrate Map
import java.util.*;
class GFG{
 
// Driver Code
public static void main(String[] args)
{
    // Empty map container
    HashMap gquiz1 = new HashMap();
 
    // Insert elements in Map
    gquiz1.put(1, 40);
    gquiz1.put(2, 30);
    gquiz1.put(3, 60);
 
    // Iterator to iterate Map
    Iterator> itr = gquiz1.entrySet().
                                              iterator();
 
    System.out.print("\nThe map gquiz1 is : \n");
    System.out.print("KEY\tELEMENT\n");
 
    // Print map gquiz1
    while(itr.hasNext())
    {
        Map.Entry entry = itr.next();
        System.out.print('\t' + entry.getKey()
                         + "\t" + entry.getValue()+ "\n");
    }
}
}
 
// This code is contributed by shikhasingrajput

蟒蛇3

# Python3 program to illustrate Map
 
# Driver Code
if __name__ == '__main__':
     
    # Empty map container
    gquiz1 = dict()
 
    # Insert elements in Map
    gquiz1[1] = 40
    gquiz1[2] = 30
    gquiz1[3] = 60
 
    print("\nThe map gquiz1 is : ")
    print("KEY\tELEMENT")
 
    for x, y in gquiz1.items():
        print(x, "\t", y)
 
# This code is contributed by Rajput-Ji

C#

// C# program to illustrate Map
using System;
using System.Collections.Generic;
 
class GFG{
 
// Driver Code
public static void Main(String[] args)
{
     
    // Empty map container
    Dictionary gquiz1 = new Dictionary();
                                             
    // Insert elements in Map
    gquiz1.Add(1, 40);
    gquiz1.Add(2, 30);
    gquiz1.Add(3, 60);
     
    Console.Write("\nThe map gquiz1 is : \n");
    Console.Write("\tKEY\tELEMENT\n");
     
    // Print map gquiz1
    foreach(KeyValuePair entry in gquiz1)
    {
        Console.Write("\t" + entry.Key +
                      "\t" + entry.Value + "\n");
    }
}
}
 
// This code is contributed by Amit Katiyar
输出:
The map gquiz1 is : 
    KEY    ELEMENT
    1    40
    2    30
    3    60

方案二:
下面是一个无序映射的说明:

C++14

// C++ program to illustrate Map
#include 
using namespace std;
 
// Driver Code
int main()
{
    // Declaring umap of 
    // type key will be of string and
    // mapped value will be of doubl
    unordered_map umap;
 
    // Insert values by using [] operator
    umap["GeeksforGeeks"] = 10;
    umap["Practice"] = 20;
    umap["Contribute"] = 30;
 
    // Traversing an unordered map
    // and print the key-value pairs
    for (auto x : umap)
        cout << x.first << " "
             << x.second << endl;
    return 0;
}

Java

// Java program to illustrate Map
import java.util.*;
 
class GFG{
 
// Driver Code
public static void main(String[] args)
{
     
    // Declaring umap of 
    // type key will be of String and
    // mapped value will be of doubl
    HashMap umap = new HashMap<>();
 
    // Insert values by using [] operator
    umap.put("GeeksforGeeks", 10);
    umap.put("Practice", 20);
    umap.put("Contribute", 30);
 
    // Traversing an unordered map
    // and print the key-value pairs
    for(Map.Entry x : umap.entrySet())
        System.out.print(x.getKey() + " " +
                         x.getValue() + "\n");
}
}
 
// This code is contributed by amal kumar choubey

C#

// C# program to illustrate Map
using System;
using System.Collections.Generic;
class GFG{
 
    // Driver Code
    public static void Main(String[] args)
    {
 
        // Declaring umap of 
        // type key will be of String and
        // mapped value will be of doubl
        Dictionary umap = new Dictionary();
 
        // Insert values by using [] operator
          umap.Add("Contribute", 30);
        umap.Add("GeeksforGeeks", 10);
        umap.Add("Practice", 20);       
 
        // Traversing an unordered map
        // and print the key-value pairs
        foreach(KeyValuePair x in umap)
            Console.Write(x.Key + " " + x.Value + "\n");
    }
}
 
// This code is contributed by Rajput-Ji
输出:
Contribute 30
GeeksforGeeks 10
Practice 20

方案三:
下面是多图的说明:

C++14

// C++ program to illustrate Multimap
#include 
using namespace std;
 
// Driver Code
int main()
{
    // Empty multimap container
    multimap gquiz1;
 
    // Insert elements
    gquiz1.insert(pair(1, 40));
    gquiz1.insert(pair(2, 30));
 
    // Iterator
    multimap::iterator itr;
 
    cout << "\nThe multimap gquiz1 is : \n";
    cout << "\tKEY\tELEMENT\n";
 
    // Print multimap gquiz1
    for (itr = gquiz1.begin();
         itr != gquiz1.end(); ++itr) {
 
        cout << '\t' << itr->first
             << '\t' << itr->second
             << '\n';
    }
    return 0;
}
输出:
The multimap gquiz1 is : 
    KEY    ELEMENT
    1    40
    2    30

程序4:
下面是一个无序多图的说明:

C++14

// C++ program to illustrate
// unordered multimap
#include 
using namespace std;
 
// Driver Code
int main()
{
    // Empty initialization
    unordered_multimap umm1;
 
    // Initialization by intializer list
    unordered_multimap umm2(
        { { "apple", 1 },
          { "ball", 2 },
          { "apple", 10 },
          { "cat", 7 },
          { "dog", 9 },
          { "cat", 6 },
          { "apple", 1 } });
 
    // Traversing an unordered_multimap
    // and print the elements stored
    for (auto x : umm2) {
        cout << x.first << " "
             << x.second << endl;
    }
    return 0;
}
输出:
dog 9
cat 6
cat 7
ball 2
apple 1
apple 10
apple 1

数组和映射的区别

Array Map
An Array is a collection of elements of the same data type. The map is a hashed structure of key and value pairs.
The indices of the list are integers starting from 0. The keys of the Map can be of any data type.
The elements are accessed via indices. The elements are accessed via key-values.
The order of the elements entered is maintained. There is no guarantee for maintaining order.
The array can be 1D, 2D or multidimensional Maps can be multimap, Unordered Multimap, Unordered map, etc
Array’s size must be specified during the array declaration. The map’s size is dynamic.

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live