C++ 教程 在线

1969cpp-pointer-to-an-array

C++ 中,将 char *char[] 传递给 cout 进行输出,结果会是整个字符串,如果想要获得字符串的地址(第一个字符的内存地址),可使用以下方法:

强制转化为其他指针(非 char*)。可以是 void *,int *,float *, double * 等。* 使用 &s[0] 不能输出 s[0](首字符)的地址。因为 &s[0] 将返回 char*,对于 char*char 指针),cout 会将其作为字符串来处理,向下查找字符并输出直到字符结束 *

#include <iostream>
 
using namespace std;
const int MAX = 3;
 
int main ()
{
   char  var[MAX] = {'a', 'b', 'c'};
   char  *ptr;
 
   // 指针中的数组地址
   ptr = var;
            
   for (int i = 0; i < MAX; i++)
   {
      cout << "Address of var[" << i << "] = ";
      cout << (int *)ptr << endl;
 
      cout << "Value of var[" << i << "] = ";
      cout << *ptr << endl;
 
      // 移动到下一个位置
      ptr++;
   }
   return 0;
}

输出结果:

Address of var[0] = 0x7fffd63b79f9
Value of var[0] = a
Address of var[1] = 0x7fffd63b79fa
Value of var[1] = b
Address of var[2] = 0x7fffd63b79fb
Value of var[2] = c

1968cpp-multi-dimensional-arrays

如果想从键盘中获取值,来构建二维数组,可以使用如下写法构建:

#include <cstdio> 
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
    vector< vector<int> > arry; //写成arry(5) 可理解为设定大小5行 
    vector<int> d;        //定义一个一维的数组; 
    int i, j, k, n;
    int number;
    
    scanf("%d", &n );
    /*可以这样实现对vector二维的初始化,得到的是n行n列的矩阵*/ 
    for( i=0; i<n; i++ ){ 
        for( j=0; j<n; j++ ){
            scanf("%d", &number );
            d.push_back( number ); 
        }
        sort( d.begin(), d.end() ); //pai xu xuyao头文件algorithm 
        arry.push_back( d );
        //d.clear();        //清空一维的数组 
        d.resize(0);
    }
    /*遍历输出*/ 
    if( arry.empty() )
        printf("0\n");
    else{
        for( i=0; i<arry.size(); i++ ) {
            for( j=0; j<arry[0].size(); j++ ){
                printf("%d ", arry[i][j] );
            }
            printf("\n");
        }
    } 
    
    return 0;
}

1967cpp-function-call-by-reference

这里利用了数异或的性质,一个数与其本身异或等于 0,0 与一个数异或不改变该数。说到 swap,我想起了优化的 swap,可能稍微难理解一点。

int swap(int& a, int& b)
{
    int temp;
    temp = a ^ b;
    a = temp ^ a;
    b = temp ^ b;
    return 0;
}

这里利用了数异或的性质,一个数与其本身异或等于 0,0 与一个数异或不改变该数。

1966cpp-function-call-by-value

使用异或运算交换两数的值:

#include <iostream>
using namespace std;
void swap(int a, int b)
{
    a=a^b;
    b=a^b;
    a=a^b;
    return;
}
int main ()
{
   // 局部变量声明
   int a = 100;
   int b = 200;
 
   cout << "交换前,a 的值:" << a << endl;
   cout << "交换前,b 的值:" << b << endl;
 
   // 调用函数来交换值
   swap(a, b);
 
   cout << "交换后,a 的值:" << a << endl;
   cout << "交换后,b 的值:" << b << endl;
 
   return 0;
}

更多内容参考:C 关于使用异或运算交换两数的值

1965cpp-function-call-by-value

不用临时变量:

#include <iostream>
using namespace std;
void swap(int a, int b)
{
    a=a+b;
    b=a-b;
    a=a-b;
    return;
}
int main ()
{
   // 局部变量声明
   int a = 100;
   int b = 200;
 
   cout << "交换前,a 的值:" << a << endl;
   cout << "交换前,b 的值:" << b << endl;
 
   // 调用函数来交换值
   swap(a, b);
 
   cout << "交换后,a 的值:" << a << endl;
   cout << "交换后,b 的值:" << b << endl;
 
   return 0;
}