年终大学习之C++学习笔记(一) ——auto泛型

    迟迟没有写C++的笔记,主要还是基础不是太够,而且就是听的还是比较模糊的,不过也没事,从第一步开始,慢慢来吧。

 这一节讲的是auto的用法

    auto 首先是自动变量类型,即可以自动获取该变量的类型,输出,是泛型编程中很重要的关键词。

    例子:

void main1()
{
	auto num = 10.9;//自动变量,自动匹配类型
	auto numA = 10/3.0;
	std::cout << num <<"     " << numA << std::endl;
	system("pause");


}

    个人感觉,auto就好似动态语言中的变量,例如我最爱的Python,就可以直接对一个变量进行赋值而不需要对其进行单独的类型声明。这在我们并不知道某个变量是什么类型时,即泛型编程是,起到了很大的作用。

    auto在C++中还有一种独特的用处,就是可以实现一维数组的自动循环。

    例子:

void main()
{
	double num[10] = { 1.0, 2.0, 3.0, 4.5, 5, 6, 7, 8, 9, 10 };
	//num数组名是一个指针常量
	//auto 自动循环 begin  endl;,必须是一个数组的常量
	//
	for (auto data : num)//泛型C++语法,循环一维数组,常量
	{
		std::cout << data<<std::endl;
		
	}
	system("pause");


}
   值得注意的是,auto的这种用法一般就适合在一维数组中使用,因为此时的数组长度是固定的,即必须是常量,而二维数组及以上就使用了指针,而指针指向的地址不是固定的。

   不过用auto进行循环就可以减少代码的重复率了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供一个C语言的循环链表实现。以下是代码示例: ``` #include <stdio.h> #include <stdlib.h> typedef struct node { void *data; struct node *next; } Node; typedef struct list { Node *head; Node *tail; int size; } List; List *createList() { List *list = (List *)malloc(sizeof(List)); list->head = NULL; list->tail = NULL; list->size = ; return list; } void add(List *list, void *data) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = data; newNode->next = NULL; if (list->size == ) { list->head = newNode; list->tail = newNode; newNode->next = list->head; } else { list->tail->next = newNode; list->tail = newNode; newNode->next = list->head; } list->size++; } void removeNode(List *list, Node *node) { if (list->size == ) { return; } if (node == list->head) { list->head = node->next; list->tail->next = list->head; } else { Node *current = list->head; while (current->next != node) { current = current->next; } current->next = node->next; if (node == list->tail) { list->tail = current; } } free(node); list->size--; } void *get(List *list, int index) { if (index < || index >= list->size) { return NULL; } Node *current = list->head; for (int i = ; i < index; i++) { current = current->next; } return current->data; } void destroyList(List *list) { while (list->size > ) { removeNode(list, list->head); } free(list); } int main() { List *list = createList(); int a = 1; float b = 2.; char c = 'c'; add(list, &a); add(list, &b); add(list, &c); printf("%d\n", *(int *)get(list, )); printf("%f\n", *(float *)get(list, 1)); printf("%c\n", *(char *)get(list, 2)); destroyList(list); return ; } ``` 这个循环链表可以存储任意类的数据,只需要将数据的地址传递给add函数即可。您可以根据需要修改代码以适应您的具体应用场景。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值