C++ 之 基础回顾(一)

1  C++ program

  

1.1  the miminal cpp

int main(){}    // the minimal C++ program

1.2  Hello World

#include <iostream>

int main()
{
    std::cout << "Hello, World!\n";
}

1.3  functions

#include <iostream>
using namespace std;

double square(double x)
{
    return x*x;
}

void print_square(double x)
{
    cout << "the square of " << x << " is " << square(x) << "\n";
}

int main()
{
    print_square(1.2);
}

2  Types, Variables and Arithmetic

2.1  definition

A declaration is a statement that introduces a name into the program. It specifies a type for the named entity:

- A type defines a set of possible values and a set of operations (for an object).

- An object is some memory that holds a value of some type.

- A value is a set of bits interpreted according to a type.

- A variable is a named object.

bool    // Boolean, possible values are true and false
char    // character, for example, ‘a‘, ‘ z‘, and ‘9‘
int     // integer, for example, 1, 42, and 1066
double  // double-precision floating-point number, for example, 3.14 and 299793.0

2.2  sizeof(char)

  

2.3  initialization

double d1 = 2.3;
double d2 {2.3};

complex<double> z = 1;      // a complex number with double-precision floating-point scalars
complex<double> z2 {d1,d2};
complex<double> z3 = {1,2};    // the = is optional with {...}
vector<int> v {1,2,3,4,5,6};  // a vector of ints

"=" is traditional and dates back to C, but if in doubt, use the general {}-list form

c++11 auto

auto b = true;     // a bool
auto ch = ‘x‘;     // a char
auto i = 123;      // an int
auto d = 1.2;      // a double
auto z = sqrt(y);  // z has the type of whatever sqrt(y) returns

We use auto where we don’t hav e a specific reason to mention the type explicitly. ‘‘Specific reasons’’ include:

- The definition is in a large scope where we want to make the type clearly visible to readers of our code.

- We want to be explicit about a variable’s range or precision (e.g., double rather than float ).

3  Constants

3.1 const and constexpr

  const :meaning roughly ‘‘I promise not to change this value’’. This is used primarily to specify interfaces, so that data can be passed to functions without fear of it being modified. The compiler enforces the promise made by const .

const int dmv = 17;    // dmv is a named constant
int var = 17;          // var is not a constant
constexpr double max1 = 1.4∗square(dmv);   // OK if square(17) is a constant expression
constexpr double max2 = 1.4∗square(var);   // error : var is not a constant expression
const double max3 = 1.4∗square(var);       // OK, may be evaluated at run time

constexpr :meaning roughly ‘‘to be evaluated at compile time’’. This is used primarily to specify constants, to allow placement of data in memory where it is unlikely to be corrupted, and for performance.

double sum(const vector<double>&);    // sum will not modify its argument
vector<double> v {1.2, 3.4, 4.5};     // v is not a constant
const double s1 = sum(v);             // OK: evaluated at run time
constexpr double s2 = sum(v);         // error : sum(v) not constant expression

3.2  constexpr function

For a function to be usable in a constant expression, that is, in an expression that will be evaluated by the compiler, it must be defined constexpr

constexpr double square(double x) { return x∗x; }

To be constexpr , a function must be rather simple: just a return -statement computing a value.

A constexpr function can be used for non-constant arguments, but when that is done the result is not a constant expression.

4  Loops

4.1  if

bool accept()
{
    cout << "Do you want to proceed (y or n)?\n";    // write question

    char answer = 0;
    cin >> answer;                                  // read answer

    if(answer == ‘y‘) return true;
    return false;
}

4.2  switch

bool accept2()
{
    cout << "Do you want to proceed (y or n)?\n";    // write question

    char answer = 0;
    cin >> answer;                                  // read answer

    switch(answer) {
    case ‘y‘:
        return true;
    case ‘n‘:
        return false;
    default:
        cout << "I will take that for a no.\n";
        return false;
    }
}

4.3  while

bool accept3()
{
    int tries = 1;
    while(tries < 4){
        cout << "Do you want to proceed (y or n)?\n";    // write question
        char answer = 0;
        cin >> answer;                                  // read answer

        switch(answer) {
        case ‘y‘:
            return true;
        case ‘n‘:
            return false;
        default:
            cout << "Sorry, I don‘t understand that.\n";
            ++tries;        // increment
        }
    }
    cout << "I‘ll take that for a no.\n";
    return false;
}

5  Pointers and Arrays

5.1  [] and *

[ ] means ‘‘array of’’ and ∗ means ‘‘pointer to.’’

char v[6];   // array of 6 characters
char∗ p;     // pointer to character

prefix unary ∗ means ‘‘contents of’’ and prefix unary & means ‘‘address of.’’

char∗ p = &v[3];     // p points to v’s four th element
char x = ∗p;         // *p is the object that p points to

  

T a[n];   // T[n]: array of n Ts
T∗ p;    // T*: pointer to T
T& r;    // T&: reference to T
T f(A);   // T(A): function taking an argument of type A returning a result of type T

5.2  copy and print

copy elements from one array to another

void copy_fct()
{
    int v1[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    int v2[10];

    for(auto i=0; i!=10; ++i)     // copy elements
        v2[i] = v1[i];
}

for every element of v , from the first to the last, place a copy in x and print it.

void print()
{
    int v[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    for(auto x : v)          // range-for-statement
        std::cout << x << ‘\n‘;

    for(auto x : {21, 32, 43, 54, 65})
        std::cout << x << ‘\n‘;
}

5.3  increment and count

void increment()
{
    int v[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    for(auto &x : v)
        ++x;
}

the suffix & means ‘‘reference to.’’ It‘s similar to a pointer, except that no need to use a prefix ∗ to access the value referred to by the reference

// count the number of occurrences of x in p[]
// p is assumed to point to a zero-ter minated array of char (or to nothing)
int count_x(char* p, char x)
{
    if(p==nullptr) return 0;
    int count = 0;
    for(; *p!=0; ++p)
        if(*p == x)
            ++count;
    return count;
}

其中,nullptr 参见博文 C++11 之 nullptr

时间: 2024-10-12 14:58:06

C++ 之 基础回顾(一)的相关文章

【DAY26】JAVA 基础回顾

基础回顾 ---------------- 1.跨平台 os JVM : sandbox 1995 2.基本数据类型 byte //1 -128 ~ 127 short //2 -32768 - 32767 int //4 long //8 float //4 doule //8 char //2 boolean //1 3.引用类型 [] class interface 4.运算符 && //短路 || //短路 & // | // ^ //抑或,相同0,不同为1 >>

Linux基础回顾(2)——Linux系统分区二三事

问题来自Linux教材,答案自我整理难免会有不足之处.这是我Linux期末的总结 1. 一块硬盘上可以有几种类型的分区?各自可以有多少个?(各个分区能安装操作系统吗?) 硬盘分区有三种类型的分区:主分区,扩展分区,逻辑分区:一个硬盘最多能划分4个主分区,或者3个主分区加上一个扩展分区,扩展分区上可以划分多个逻辑分区(最多20个).能安装操作系统. 2.用户能否在安装过程中创建扩展分区呢? 分区工具在文件系统类型中没有提供扩展(extended)分区类型,即用户不能根据需要不能手工创建扩展分区.安

PHP移动互联网开发笔记(6)——MySQL数据库基础回顾

最近看了一些架构方面的资料,但是发现基础知识都不怎么牢固,接下来的一段时间,我会定期总结基础知识. 一.数据类型 1.整型 数据类型 存储空间 说明 取值范围 TINYINT 1字节 非常小的整数 带符号值:-128~127 无符号值:0~255 SMALLINT 2字节 较小的整数 带符号值:-32768~32767 无符号值:0~65535 MEDIUMNT 3字节 中等大小的整数 带符号值:-8388608~8388607 无符号值:0~16777215 INT 4字节 标准整数 带符号值

[C#] C# 基础回顾 - 匿名方法

C# 基础回顾 - 匿名方法 目录 简介 匿名方法的参数使用范围 委托示例 简介 在 C# 2.0 之前的版本中,我们创建委托的唯一形式 -- 命名方法. 而 C# 2.0 -- 引进了匿名方法,在 ≥ C# 3.0 的版本中,我们会用 Lambda 表达式进行取代匿名方法,并且用 Lambda 表达式作为编写内联代码的首选方式,因为它更简洁. 匿名方法是,顾名思义,匿名方法就是没有名称的方法.匿名方法最明显的好处就是:可以降低额外另写一个方法的工作量:另外一个好处就是可以直接访问调用者的变量,

四、Android学习第四天——JAVA基础回顾(转)

(转自:http://wenku.baidu.com/view/af39b3164431b90d6c85c72f.html) 四.Android学习第四天——JAVA基础回顾 这才学习Android的第四天,在程序中已经遇到了JAVA中以前不常用的一些知识点,赶紧回顾复习一下,打下基础 这里就做个简单的小结: 一.匿名内部类 匿名内部类说白了就是个没有被命名的JAVA类 在以下条件下使用匿名内部类比较适合: ①只用到该类的一个实例时 ②类在定义后被马上用到 ③类非常小(SUN推荐是在4行代码以下

spring 基础回顾 tips01

spring 属性注入时,类中必须有setter 和 getter方法. spring配置文件中: java业务类中注入DAO: private StudentDao studentDao; // 通过属性注入 public StudentDao getStudentDao() { return studentDao; } public void setStudentDao(StudentDao studentDao) { this.studentDao = studentDao; } spri

spring 基础回顾 tips02

spring注入list .set. map. properties 1.list 在xml中这样写: <property name="list"> <list> <value>Michael Huang</value> <ref bean="student"></ref> <value>110</value> </list> </property>

1、java基础回顾与加强

一.    基础回顾 1   集合 1.1  集合的类型与各自的特性 ---|Collection: 单列集合 ---|List: 有存储顺序, 可重复 ---|ArrayList:    数组实现, 查找快, 增删慢 由于是数组实现, 在增和删的时候会牵扯到数组 增容, 以及拷贝元素. 所以慢.数组是可以直接按索引查找, 所以查找时较快 ---|LinkedList:   链表实现, 增删快, 查找慢由于链表实现, 增加时只要让前一个元素记住自己就可以, 删除时让前一个元素记住后一个元素, 后

基础回顾:get方法和set方法(类的继承多态)

基础回顾:get方法和set方法 定义类成员变量时,可以在@interface中定义,也可以在@implementation中定义: 在@interface中声明,成员变量的状态是受保护的,即“@protected”: 在@implementation中声明,成员变量的状态是私有的,即“@private” 在类的外面,是无法直接访问成员变量的,只有将成员变量修改为@public时,才可以外部访问. 使用@public时,访问成员变量使用“->”,如: time->hour=25; 但使用@pu

JavaScript 基础回顾——对象

JavaScript是基于对象的解释性语言,全部数据都是对象.在 JavaScript 中并没有 class 的概念,但是可以通过对象和类的模拟来实现面向对象编程. 1.对象 在JavaScript中,对象被定义为无序属性的集合,属性可以是任何类型的值,包括其他对象或函数.函数作为属性值时称为“方法”,即对象的行为. (1)对象常用的内部属性 对象的内部属性是由JavaScript 规范定义的,由运行代码的系统来访问.对象常用的内部属性: prototype        对象        获