工具
- Notepad++
- VS 2015开发人员命令提示符
特点轻量化,Notepad++可以写源代码,在VS 2015开发人员命令提示符可以进行编译、运行。
cd xxxxxx //进入源文件所在目录
cl xxx.cpp //在VS 2015开发人员命令提示符中编译源代码
xxx.exe //运行编译后的可执行文件
基础知识
循环语句
#include<iostream>int main()
{int sum = 0, val = 1;while (val <=10) //括号内表达式结果必须是bool或可以转换为bool{sum += val;++val;}std::cout<<"sum of 1 to 10 inclusive is "<< sum <<std::endl;int sumf = 0;for(int valf = 0; valf <= 10; ++valf){sumf += valf;}std::cout<<"sum of 1 to 10 inclusive is "<< sumf <<std::endl;return 0;
}
一个接收输入的程序:
#include<iostream>int main()
{int sum = 0, val = 0;while (std::cin >> val) //std是所有标准库的命名空间{sum += val;} //使用 ctrl + Z 来输入文件结束的符号std::cout<<"sum is: "<< sum <<std::endl;return 0;
}
如:
2
3
43
32
54
645
^Z
sum is: 779
数组
数组简介
数组中的操作
#include<iostream>
#include<stdio.h>
#include<algorithm> //包含sort函数
using namespace std;int main()
{//1. Initializationint a[5] = { 1, 2, 3 }; //other element will be set as the default value//2. Get Lengthint size = sizeof(a) / sizeof(*a); //sizeof用于获取变量或数据类型字节大小,不同机器结果不同//除以数组单个元素字节大小,可以得到数组长度cout << "The size of a1 is: " << size << endl;//3. Iterate all Elementscout << "The contents of a1 are:";for (int item : a)//在C++11中终于有基于范围的for循环(The range-based for statement)//在上面基于范围的for循环中,在item的定义之后,紧跟一个冒号(:),//之后直接写上需要遍历的表达式,for循环将自动以表达式返回的容器为范围进行迭代//这里在使用只读方式遍历容器{cout << " " << item;}cout << endl;// 4. Modify Elementa[0] = 4;// 5. Sort:需要头文件<algorithm>sort(a, a + size); //sort(begin, end, cmp),//其中begin为指向待sort()的数组的第一个元素的指针,//end为指向待sort()的数组的最后一个元素的下一个位置的指针,//cmp参数为排序准则,如果没有的话,默认以非降序排序。cout << "The contents of new a1 are:";for (int& item : a)//在遍历时修改容器中的值{cout << " " << ++item;}cout << endl;getchar();return 0;
}
动态数组简介
在 C++ 中的 vector,是内置的动态数组,其仍然是一个随机存取的列表数据结构,但大小是可变的。可以简单的认为,向量是一个能够存放任意类型的动态数组。其提供了在序列末尾相对快速地添加/删除元素的操作。
一道Leetcode题目:
在一个给定的数组nums中,总是存在一个最大元素 。
查找数组中的最大元素是否至少是数组中每个其他数字的两倍。
如果是,则返回最大元素的索引,否则返回-1。
提示:
nums 的长度范围在[1, 50].
每个 nums[i] 的整数范围在 [0, 100].
class Solution {
public:int dominantIndex(vector<int>& nums) {//需要两个整数变量,一个保存数组最大值元素,一个保存其索引int large = nums[0], index = 0, temp;//第一次遍历,找出最大值及其索引for(int i = 0; i < nums.size(); ++i){if (nums[i] > large){large = nums[i];index = i;}}//第二次遍历,将最大值与其它值比较for(int i = 0; i < nums.size(); ++i){if(i != index){temp = nums[i];if(large < 2 * temp)return -1;}}return index;}
};
一个更好的解法:
一次遍历找到最大的数max1和第二大的数max2,然后看看最大的数是不是大于等于第二大的数的两倍