vector与array对比

  1. 首先,vector类似于数组,有一段连续的内存,有固定的起始地址,可进行随机存取操作,即可以像数组一样用[ ]操作符进行元素的随机访问
  2. 另外,vector和数组一样,都可以存放任意对象,但除了引用,即不存在引用的数组和引用的vector。
  3. vector是一个能存放任意类型的动态数组,是动态连续空间是一种顺序的容器(vector也可以看作是向量)

数组对比vector的的缺点

  1. 首先数组的长度必须是常量表达式,并且在初始化的时候就应该给出来。

  2. 数组之间不能够进行整体之间的复制,但是vector容器可以进行整体之间的赋值。

  3. 数组使用的时候下标容易越界,虽然vector也可以使用下标来访问容器中的数据,但是vector可以使用较多的机制来控制,比如用迭代器。

    还有一点要说一下,数组名和容器名是有区别的,数组名不仅表示数组的名称,还代表了数组的首地址,数组名有时候可看作指针,并使

用一些类似于指针的操作,例如初始化了一个数组 int a[10];可进行如下操作,a+4、*(a+5)等来访问a中的数据。而容器名的话就仅仅只是

容器的名称了,它没有类似于数组名的那些操作。

最后说一下二者的使用情况,在不需要变长且容量较小的时候用array;需要变长,容量较大的时候就用vector

#include<iostream>
#include<vector>
using namespace std;
int main()
{
	int a1[3][3];
	int lines1 = sizeof(a1) / sizeof(a1[0][0]);
	int row1 = sizeof(a1) / sizeof(a1[0]);
	int column1 = lines1 / row1;
	cout << sizeof(a1) << endl;
	cout << lines1 << "  " << row1 << "  " << column1 << endl;

	vector<vector<int>> a(3, vector<int>(3, 0));
	int lines = sizeof(a) / sizeof(a[0][0]);
	int row = sizeof(a) / sizeof(a[0]);
	int column = lines / row;
	cout << sizeof(vector<int>) << endl;
	cout << sizeof(a) << endl;
	cout <<lines << "  " << row << "  " << column << endl;
}

result

36
9  3  3
32
32
8  1  8

分析结果:

  1. 这里使用的是vs的debug模式,64位编译器模式。用vector定义的二维数组名a代表数组的首地址,可以看作类型位vector的指针。在64位编译器的release模式下,sizeof(a)=24,包括一个头指针、一个尾指针和一个分配的内存的下一个地址(这里是老师说的,我也不太明白)。在debug模式下可能多了一个padding信息,所以多出八个字节。
  2. 所以row是1是因为sizeof(a)和sizeof(a[0])都是对vector的大小求值。 另外vector是动态数组,其数据最终是存在堆上,vector对象本身大小固定,被存在栈上
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是 SaDE 算法的 Python 代码: ```python import numpy as np def SaDE(F, bounds, popsize=100, maxiter=1000, p=0.1, c=0.5, seed=None): """ Scalable Distributed Evolutionary Algorithm (SaDE) Parameters ---------- F : function The objective function to be minimized. It should take a 1-D numpy array as input and return a scalar value. bounds : array_like The bounds of the search space. It should be a list of tuples, where each tuple corresponds to the lower and upper bounds of a dimension. popsize : int, optional The population size. Default is 100. maxiter : int, optional The maximum number of iterations. Default is 1000. p : float, optional The probability of selecting the best solution as the base vector. Default is 0.1. c : float, optional The probability of selecting each component of the donor vector from the corresponding component of the base vector. Default is 0.5. seed : int, optional The random seed. Default is None. Returns ------- x : array_like The best solution found by the algorithm. f : float The corresponding function value. """ # Set random seed if seed is not None: np.random.seed(seed) # Initialize population D = len(bounds) pop = np.random.rand(popsize, D) * (bounds[:, 1] - bounds[:, 0]) + bounds[:, 0] fitness = np.array([F(x) for x in pop]) best_idx = np.argmin(fitness) best_x, best_f = pop[best_idx], fitness[best_idx] # Main loop for t in range(maxiter): # Select the best solution as the base vector base_idx = np.argmin(fitness) base_x = pop[base_idx] # Generate the donor vector donor_x = np.copy(base_x) for i in range(D): if np.random.rand() < c: idxs = np.random.choice(popsize, 3, replace=False) diff = pop[idxs[0]] - pop[idxs[1]] donor_x[i] += p * diff[i] donor_x[i] += (1 - p) * (pop[idxs[2], i] - base_x[i]) # Evaluate the donor vector donor_f = F(donor_x) # Update the population if donor_f < fitness[base_idx]: pop[base_idx] = donor_x fitness[base_idx] = donor_f # Update the best solution best_idx = np.argmin(fitness) if fitness[best_idx] < best_f: best_x, best_f = pop[best_idx], fitness[best_idx] return best_x, best_f ``` 以下是标准差分进化算法(DE)的 Python 代码: ```python import numpy as np def DE(F, bounds, popsize=100, maxiter=1000, F=0.5, CR=0.9, seed=None): """ Differential Evolution (DE) Parameters ---------- F : function The objective function to be minimized. It should take a 1-D numpy array as input and return a scalar value. bounds : array_like The bounds of the search space. It should be a list of tuples, where each tuple corresponds to the lower and upper bounds of a dimension. popsize : int, optional The population size. Default is 100. maxiter : int, optional The maximum number of iterations. Default is 1000. F : float, optional The scaling factor. Default is 0.5. CR : float, optional The crossover probability. Default is 0.9. seed : int, optional The random seed. Default is None. Returns ------- x : array_like The best solution found by the algorithm. f : float The corresponding function value. """ # Set random seed if seed is not None: np.random.seed(seed) # Initialize population D = len(bounds) pop = np.random.rand(popsize, D) * (bounds[:, 1] - bounds[:, 0]) + bounds[:, 0] fitness = np.array([F(x) for x in pop]) best_idx = np.argmin(fitness) best_x, best_f = pop[best_idx], fitness[best_idx] # Main loop for t in range(maxiter): for i in range(popsize): # Select three different solutions idxs = np.random.choice(popsize, 3, replace=False) x1, x2, x3 = pop[idxs] # Generate a trial vector v = x1 + F * (x2 - x3) # Perform crossover u = np.copy(pop[i]) jrand = np.random.randint(D) for j in range(D): if np.random.rand() < CR or j == jrand: u[j] = v[j] # Evaluate the trial vector f = F(u) # Update the population if f < fitness[i]: pop[i] = u fitness[i] = f # Update the best solution best_idx = np.argmin(fitness) if fitness[best_idx] < best_f: best_x, best_f = pop[best_idx], fitness[best_idx] return best_x, best_f ``` 为了可视化对比两种算法的区别,我们可以用 Matplotlib 绘制算法的优化轨迹。以下是一个简单的示例代码,用于绘制 Rastrigin 函数的优化轨迹: ```python import matplotlib.pyplot as plt def rastrigin(x): return 10 * len(x) + np.sum(x**2 - 10 * np.cos(2 * np.pi * x)) bounds = [(-5.12, 5.12)] * 2 x_sade, f_sade = SaDE(rastrigin, bounds) x_de, f_de = DE(rastrigin, bounds) fig, ax = plt.subplots(figsize=(8, 6)) ax.contourf(X, Y, Z, levels=100) ax.plot(*zip(*x_sade_traj), color='red', label='SaDE') ax.plot(*zip(*x_de_traj), color='blue', label='DE') ax.scatter(*x_sade, color='red', marker='*', s=200) ax.scatter(*x_de, color='blue', marker='*', s=200) ax.legend() plt.show() ``` 这段代码会绘制 Rastrigin 函数的等高线图和两种算法的优化轨迹。其中,红色表示 SaDE 算法的优化轨迹,蓝色表示 DE 算法的优化轨迹。我们可以看到,SaDE 算法的优化轨迹更加平滑,收敛速度更快,而 DE 算法的优化轨迹更加抖动,收敛速度更慢。 当然,这只是一个简单的可视化示例,实际情况下两种算法的效果会受到很多因素的影响,如参数的选择、搜索空间的维度、目标函数的特性等等。因此,我们需要根据具体的问题来选择适合的优化算法。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

星光技术人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值