Table of Contents
可以
int a[3][3];
但不可以
int a[n][m];
所以有动态初始化的需求 使用 new 实现
messet
void * memset ( void * ptr, int value, size_t num );
为特定内存块设置值
erase注意注意事项¶
vector 或者 string 等 STL 容器,如果调用 erase 方法将其中的某个值删除的话,后序的元素会自动补上前面的空位。
vector::erase
iterator erase (const_iterator position);
iterator erase (const_iterator first, const_iterator last);
参数必须是 iterator 删除 vector 中特定项
#include <iostream>
#include <vector>
using namespace std;
//二维数组初始化
int initialize_dynamic_2d_array()
{
int n = 3, m = 3;
int** arr = new int*[n];
for (int i = 0; i != m; i++)
{
arr[i] = new int[m];
memset(arr[i], 0, m * sizeof(int));//并非必须
}
for (int i = 0; i != n; i++)
{
for (int j = 0; j != m; j++)
{
arr[i][j] = n * i + j;
}
}
for (int i = 0; i != n; i++)
{
for (int j = 0; j != m; j++)
{
cout << arr[i][j];
}
}
cout << endl << endl;
return 0;
}
//二维 vector 初始化方法
int initialize_2dvector()
{
int row = 5, col = 3;
vector<vector<int>> arr(row);
for (int i = 0; i != row; i++)
{
arr[i].resize(col);
}
arr[1][0] = 10;
//输出2d vector
for (int i = 0; i != row; i++)
{
for (int j = 0; j != col; j++)
{
cout << arr[i][j];
}
}
cout << endl << endl;
return 0;
}
//vector erase 测试
int vector_erase_test()
{
vector<int> arr_1(10);
for (int i = 0; i < 10; i++) arr_1[i] = i;
arr_1.erase(arr_1.begin() + 3);
for (vector<int>::iterator iter = arr_1.begin(); iter != arr_1.end(); iter++)
{
cout << *iter;
}
cout << endl << endl;
int row = 3, col = 3;
vector<vector<int>> arr_2(row);
for (int i = 0; i != row; i++)
{
arr_2[i].resize(col);
for (int j = 0; j != arr_2[i].size(); j++)
{
arr_2[i][j] = row * i + j;
}
}
cout << "arr_2 size " << arr_2.size() << endl;
arr_2.erase(arr_2.begin());
//arr_2 size 实时变小
arr_2[0].erase(arr_2[0].begin());
for (int i = 0; i != arr_2.size(); i++)
{
for (int j = 0; j != arr_2[i].size(); j++)
{
cout << arr_2[i][j];
}
}
cout << endl << "arr_2 size " << arr_2.size();
cout << endl << endl;
return 0;
}
int main()
{
initialize_dynamic_2d_array();
initialize_2dvector();
vector_erase_test();
system("pause");
return 0;
}
012345678
0001000000000000
012456789
arr_2 size 3 45678 arr_2 size 2