【无标题】

这篇博客介绍了C++中的数组操作,包括固定大小的数组与vector的性能对比、数组的初始化方式、访问数组元素的技巧,以及通过指针遍历数组。还展示了如何用begin和end函数处理数组,并提供了两个实践例子:数组元素置零和比较两个数组是否相等。
摘要由CSDN通过智能技术生成

C++ Premier之3.5:数组

相比vector,数组大小固定,损失了一定的灵活性,但是性能稳定。

初始化

初始化数组时,维度必须是一个常量

  constexpr unsigned sz = 42;
  int arr[10];
  int* parr[sz];
  string bad[cnt];//错误
  string good[sz];
  string strs[get_size()];//错误
//显式初始化
  const unsigned sz = 3;
  int ia1[sz] = { 1,2,3 };
  int a2[] = { 2,3,4 };
  int a3[53] = { 3,4,5 };
  string a4[4] = {"hello","olleh"}//未定义部分自动补0,补“”
  //可以使用字符串字面值进行初始化,但不可以拷贝和赋值
  
char a3[] = "c++";
int a2[] = a3;//非法

访问数组元素

1、使用 数组记录考试成绩段

int main() {
	unsigned scores[5] = {};//分为5段
	unsigned grade;
	while (cin >> grade) {//ctrl+z+回车,输入结束
		scores[grade / 25] = scores[grade / 25] + 1;
	}
	//使用sizeof获取数组的长度
	for (int i = 0; i < sizeof(scores) / sizeof(scores[0]);i++) {
		cout << scores[i] <<" ";
	}
	cout << "sizeof(scores)" << sizeof(scores) << ";" << sizeof(scores[0]) << endl;
	return 0;
}

运行结果:
在这里插入图片描述

指针和数组

利用数组名的指针特性输出数组arr的全部元素

	int a[] = {0,1,2,3,4,5,6,7,8,9}
	int *e = a[10]
	for(int *b = arr;b!=e;++b)
		cout<<*b<<endl;

begin、end与数组

	int a[] = {0,1,2,3,4,5,6,7,8,9};
	int* pbeg = begin(arr),;pend = end(arr);
	while(pbeg != pend && >=0)
		++pbeg;

练习

3.34 数组元素置零

int main() {
  int a[5] = { 1,2,2,3,4 };
  int* pa = a;
  for (int i = 0; i < 5; ++i) {
  	*(pa + i) = 0;
  	cout << a[i] << endl;
  }
  return 0;
}

3.35比较数组是否相等

#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
bool compare(int* const pb1, int* const pe1, int* const pb2, int* const pe2) {
	for (int* i = pb1, *j = pb2; (i != pe1) && (j != pe2); ++i, ++j)
		if (*i != *j) return false;
}

int main()
{
	int arr1[3] = { 0, 1, 2 };
	int arr2[3] = { 0, 2, 4 };

	if (compare(begin(arr1), end(arr1), begin(arr2), end(arr2)))
		cout << "The two arrays are equal." << endl;
	else
		cout << "The two arrays are not equal." << endl;

	cout << "==========" << endl;

	vector<int> vec1 = { 0, 1, 2 };
	vector<int> vec2 = { 0, 1, 2 };

	if (vec1 == vec2)
		cout << "The two vectors are equal." << endl;
	else
		cout << "The two vectors are not equal." << endl;

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值