迭代器的辅助函数实例

问题及代码:

/*Copyright (c)2016,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:main.cpp
*作    者:崔青青
*完成日期:2016年6月3日
*版 本 号:v1.0
*问题描述:
*输入描述:无
*输出描述:无
*/
#include <iostream>
#include<list>
#include<algorithm>
#include<iterator>
using namespace std;

int main()
{
  list<int>coll;
  for(int i=1;i<=9;i++)
  {
      coll.push_back(i);
  }
  list<int>::iterator pos=coll.begin();
  advance(pos,2);
  cout<<"value:"<<*pos<<endl;
  pos=find(coll.begin(),coll.end(),6);
  if(pos!=coll.end())
  {
      cout<<"Distance:"<<distance(coll.begin(),pos);
      cout<<endl;
  }
    return 0;
}

运行结果:


知识点总结:

从这个程序中,我们了解了advance和distance这个函数,advance可以对对象执行n次自增操作,distance可以计算两个迭代器之间的距离。

学习心得:

一开始读这种程序的时候还比较费力,练得多了之后觉得轻松多了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 智慧社区背景与挑战 随着城市化的快速发展,社区面临健康、安全、邻里关系和服务质量等多方面的挑战。华为技术有限公司提出智慧社区解决方案,旨在通过先进的数字化技术应对这些问题,提升城市社区的生活质量。 2. 技术推动智慧社区发展 技术进步,特别是数字化、无线化、移动化和物联化,为城市社区的智慧化提供了可能。这些技术的应用不仅提高了社区的运行效率,也增强了居民的便利性和安全性。 3. 智慧社区的核心价值 智慧社区承载了智慧城市的核心价值,通过全面信息化处理,实现对城市各个方面的数字网络化管理、服务与决策功能,从而提升社会服务效率,整合社会服务资源。 4. 多层次、全方位的智慧社区服务 智慧社区通过构建和谐、温情、平安和健康四大社区模块,满足社区居民的多层次需求。这些服务模块包括社区医疗、安全监控、情感沟通和健康监测等。 5. 智慧社区技术框架 智慧社区技术框架强调统一平台的建设,设立数据中心,构建基础网络,并通过分层建设,实现平台能力及应用的可持续成长和扩展。 6. 感知统一平台与服务方案 感知统一平台是智慧社区的关键组成部分,通过统一的RFID身份识别和信息管理,实现社区服务的智能化和便捷化。同时,提供社区内外监控、紧急救助服务和便民服务等。 7. 健康社区的构建 健康社区模块专注于为居民提供健康管理服务,通过整合医疗资源和居民接入,实现远程医疗、慢性病管理和紧急救助等功能,推动医疗模式从治疗向预防转变。 8. 平安社区的安全保障 平安社区通过闭路电视监控、防盗报警和紧急求助等技术,保障社区居民的人身和财产安全,实现社区环境的实时监控和智能分析。 9. 温情社区的情感沟通 温情社区着重于建立社区居民间的情感联系,通过组织社区活动、一键呼叫服务和互帮互助平台,增强邻里间的交流和互助。 10. 和谐社区的资源整合 和谐社区作为社会资源的整合协调者,通过统一接入和身份识别,实现社区信息和服务的便捷获取,提升居民生活质量,促进社区和谐。
以下是一个简单的示例代码,使用遗传算法(Genetic Algorithm,GA)优化卷积神经网络(Convolutional Neural Network,CNN): ```python import numpy as np import tensorflow as tf import random # 定义CNN架构 def cnn_architecture(x, weights, biases, keep_prob): # 第一层卷积层 conv1 = tf.nn.relu(tf.nn.conv2d(x, weights['conv1'], strides=[1, 1, 1, 1], padding='SAME') + biases['conv1']) # 第一层池化层 pool1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # 第二层卷积层 conv2 = tf.nn.relu(tf.nn.conv2d(pool1, weights['conv2'], strides=[1, 1, 1, 1], padding='SAME') + biases['conv2']) # 第二层池化层 pool2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # 全连接层 fc1 = tf.reshape(pool2, [-1, weights['fc1'].get_shape().as_list()[0]]) fc1 = tf.nn.relu(tf.matmul(fc1, weights['fc1']) + biases['fc1']) # Dropout层 fc1_drop = tf.nn.dropout(fc1, keep_prob) # 输出层 logits = tf.matmul(fc1_drop, weights['output']) + biases['output'] return logits # 定义GA的参数 POPULATION_SIZE = 100 CROSSOVER_RATE = 0.8 MUTATION_RATE = 0.1 N_GENERATIONS = 50 N_EVOLUTIONS = 20 # 定义GA的辅助函数 def normal_init(shape): return tf.Variable(tf.random.normal(shape, stddev=0.1)) def zeros_init(shape): return tf.Variable(tf.zeros(shape)) def generate_population(): population = [] for i in range(POPULATION_SIZE): weights = { 'conv1': normal_init([3, 3, 1, 32]), 'conv2': normal_init([3, 3, 32, 64]), 'fc1': normal_init([7 * 7 * 64, 1024]), 'output': normal_init([1024, 10]) } biases = { 'conv1': zeros_init([32]), 'conv2': zeros_init([64]), 'fc1': zeros_init([1024]), 'output': zeros_init([10]) } population.append((weights, biases)) return population def fitness(x_train, y_train, population): accuracies = [] for i in range(POPULATION_SIZE): weights, biases = population[i] x = tf.placeholder(tf.float32, [None, 28, 28, 1]) y = tf.placeholder(tf.float32, [None, 10]) keep_prob = tf.placeholder(tf.float32) y_pred = cnn_architecture(x, weights, biases, keep_prob) cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=y_pred)) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for j in range(N_EVOLUTIONS): batch_mask = np.random.choice(x_train.shape[0], 100) x_batch = x_train[batch_mask] y_batch = y_train[batch_mask] train_step.run(feed_dict={x: x_batch, y: y_batch, keep_prob: 0.5}) acc = accuracy.eval(feed_dict={x: x_train, y: y_train, keep_prob: 1.0}) accuracies.append(acc) return accuracies def crossover(parent1, parent2): weights1, biases1 = parent1 weights2, biases2 = parent2 child1_weights = {} child2_weights = {} child1_biases = {} child2_biases = {} for key in weights1.keys(): if random.random() < 0.5: child1_weights[key] = weights1[key] child2_weights[key] = weights2[key] else: child1_weights[key] = weights2[key] child2_weights[key] = weights1[key] for key in biases1.keys(): if random.random() < 0.5: child1_biases[key] = biases1[key] child2_biases[key] = biases2[key] else: child1_biases[key] = biases2[key] child2_biases[key] = biases1[key] return (child1_weights, child1_biases), (child2_weights, child2_biases) def mutation(individual): weights, biases = individual for key in weights.keys(): if random.random() < MUTATION_RATE: weights[key] += np.random.normal(0, 0.1, weights[key].shape) for key in biases.keys(): if random.random() < MUTATION_RATE: biases[key] += np.random.normal(0, 0.1, biases[key].shape) return weights, biases def select_population(fitnesses, population): sorted_population = sorted(list(zip(fitnesses, population)), reverse=True) selected_population = [] for i in range(POPULATION_SIZE): selected_population.append(sorted_population[i][1]) return selected_population # 加载MNIST数据集 (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_train = x_train.reshape([-1, 28, 28, 1]) / 255.0 y_train = tf.keras.utils.to_categorical(y_train, 10) # 初始化GA种群 population = generate_population() # GA主循环 for i in range(N_GENERATIONS): print('Generation', i+1) # 计算适应度 fitnesses = fitness(x_train, y_train, population) # 选择优良个体 population = select_population(fitnesses, population) # 生成新个体 new_population = [] for j in range(int(POPULATION_SIZE * CROSSOVER_RATE)): parent1 = random.choice(population) parent2 = random.choice(population) child1, child2 = crossover(parent1, parent2) child1 = mutation(child1) child2 = mutation(child2) new_population.append(child1) new_population.append(child2) for j in range(POPULATION_SIZE - len(new_population)): individual = random.choice(population) individual = mutation(individual) new_population.append(individual) population = new_population # 测试最优个体 weights, biases = select_population(fitness(x_train, y_train, population), population)[0] x = tf.placeholder(tf.float32, [None, 28, 28, 1]) y = tf.placeholder(tf.float32, [None, 10]) keep_prob = tf.placeholder(tf.float32) y_pred = cnn_architecture(x, weights, biases, keep_prob) correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) acc = accuracy.eval(feed_dict={x: x_test.reshape([-1, 28, 28, 1]) / 255.0, y: tf.keras.utils.to_categorical(y_test, 10), keep_prob: 1.0}) print('Test accuracy:', acc) ``` 这个示例代码定义了一个基本的CNN架构,包括两个卷积层、两个池化层和一个全连接层,使用Adam优化器进行训练。GA的目标是优化CNN的权重和偏置,使得在训练集上的分类精度最高。 该代码使用的方法是,先生成一个随机的种群(即多组CNN的权重和偏置),然后对每一组权重和偏置进行遗传算法优化。遗传算法每一轮迭代会根据上一轮的适应度(即训练集上的分类精度)选择一批优良个体,并使用交叉和变异操作生成新个体,组成新的种群,并继续进行迭代。最终,这个代码将测试最优个体在测试集上的分类精度。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值