0
点赞
收藏
分享

微信扫一扫

C++/C# 数据类型结构间

田妞的读书笔记 03-29 13:30 阅读 1
c++c#windows

1.C#数据结构互相转化

在C#中,可以使用各种数据结构来表示和存储数据,比如数组、列表、字典、集合等。这些数据结构之间也可以进行互相转化,下面是一些简单示例代码:

1.数组转换为列表:

int[] array = { 1, 2, 3, 4, 5 };
List<int> list = new List<int>(array);

2.列表转换为数组:

List<int> list = new List<int> { 1, 2, 3, 4, 5 };
int[] array = list.ToArray();

3.数组转换为字典:

string[] keys = { "A", "B", "C" };
int[] values = { 1, 2, 3 };
Dictionary<string, int> dictionary = Enumerable.Range(0, keys.Length).ToDictionary(i => keys[i], i => values[i]);

4.字典转换为数组:

Dictionary<string, int> dictionary = new Dictionary<string, int>
{
    { "A", 1 },
    { "B", 2 },
    { "C", 3 }
};
string[] keys = dictionary.Keys.ToArray();
int[] values = dictionary.Values.ToArray();

5.列表转换为集合:

List<int> list = new List<int> { 1, 2, 3, 4, 5 };
HashSet<int> set = new HashSet<int>(list);

6.集合转换为列表:

HashSet<int> set = new HashSet<int> { 1, 2, 3, 4, 5 };
List<int> list = new List<int>(set);

 2.C++数据结构互相转化

在C++中,可以使用各种数据结构来表示和存储数据,比如数组、向量(vector)、映射(map)、集合(set)等。这些数据结构之间也可以进行互相转化,以下是一些简单示例代码:

1.数组转换为向量(vector):

#include <vector>
#include <iostream>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);

    std::vector<int> vec(arr, arr + n);

    for (int i : vec) {
        std::cout << i << " ";
    }

    return 0;
}

2.向量(vector)转换为数组:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};

    int* arr = &vec[0];
    int n = vec.size();

    for (int i = 0; i < n; i++) {
        std::cout << arr[i] << " ";
    }

    return 0;
}

3.映射(map)转换为向量(vector):

#include <map>
#include <vector>
#include <iostream>

int main() {
    std::map<std::string, int> myMap = {{"A", 1}, {"B", 2}, {"C", 3}};

    std::vector<std::pair<std::string, int>> vec(myMap.begin(), myMap.end());

    for (auto p : vec) {
        std::cout << p.first << " : " << p.second << std::endl;
    }

    return 0;
}

4.集合(set)转换为向量(vector):

#include <set>
#include <vector>
#include <iostream>

int main() {
    std::set<int> mySet = {1, 2, 3, 4, 5};

    std::vector<int> vec(mySet.begin(), mySet.end());

    for (int i : vec) {
        std::cout << i << " ";
    }

    return 0;
}

 

举报

相关推荐

C# 数据类型

c#数据类型

C#数据类型

c++数据类型

C#数据类型转换

C# 数据类型转换

0 条评论