java和c++语法对比列表
把自己周末突击学习c++的笔记贴在这里,之后空了再整理补充。
| java | c++ |
main() |
// every function must be part of a class; the main function for a particular class file is invoked when java <class> is run (so you can have one main function per class--useful for writing unit tests for a class) class HelloWorld { public static void main(String args[]) { System.out.println( "Hello, World" ); } } |
// free-floating function int main( int argc, char* argv[]) { printf( "Hello, world" ); } |
头文件 | import java.util.*; | 比如list就需要#include<list> using namespace std; |
static method |
class MyClass { public static doStuff() { // do stuff } } // now it's used like this MyClass.doStuff(); |
class MyClass { public: static doStuff(); }; // now it's used like this MyClass::doStuff(); |
Object declarations
|
// always allocated on the heap (also, always need parens for constructor) myClass x = new myClass(); |
// on the stack myClass x; // or on the heap myClass *x = new myClass; |
访问对象域 | You always work with references (which are similar to pointers--see the next section), so you always use a dot: myClass x = new MyClass(); x.my_field; // ok | If you're using a stack-based object, you access its fields with a dot: myClass x; x.my_field; // ok But you use the arrow operator (->) to access fields of a class when working with a pointer: myClass x = new MyClass; x->my_field; // ok |
References vs. pointers
|
// references are mutable and store addresses only to objects; there are no raw pointers myClass x; x.foo(); // error, x is a null ``pointer'' // note that you always use . to access a field |
// references are immutable, use pointers for more flexibility int bar = 7, qux = 6; int& foo = bar;
|
Inheritance |
class Foo extends Bar { ... } |
class Foo : public Bar { ... }; |
Protection levels |
public void foo(); public void bar(); |
public: void foo(); void bar(); |
Virtual functions |
// functions are virtual by default; use final to prevent overriding int foo(); // or, final int foo(); |
virtual int foo(); // or, non-virtually as simply int foo(); |
Abstract classes |
// syntax allows you to be explicit! abstract class Bar { public abstract void foo(); }
// or you might even want to specify an interface interface Bar { public void foo(); }
// and later, have a class implement the interface: class Chocolate implements Bar { public void foo() { /* do something */ } } |
// just need to include a pure virtual function class Bar { public: virtual void foo() = 0; }; |
Memory management
|
// the compiler will catch the use of uninitialized references, but if you need to initialize a reference so it's known to be invalid, assign null myClass x = null; |
// initialize pointer to NULL int *x = NULL;
|
Throw Spec |
int foo() throws IOException |
int foo() throw (IOException) |
| System.out.printf(“%d\n”, a); | cout << *itnew << " "; |
| java | c++ |
Booleans |
boolean foo; |
bool foo; |
|
boolean[] notPrime = new boolean[n];//默认false |
vector<bool> notPrime(n, false); |
Const |
final int x = 7; |
const int x = 7; |
Arrays |
int[] x = new int[10]; // use x, memory reclaimed by the garbage collector or returned to the system at the end of the program's lifetime |
int x[10]; // or int *x = new x[10]; // use x, then reclaim memory delete[] x; |
Iteration
|
ArrayList myArrayList = new ArrayList(); Iterator itr = myArrayList.iterator(); while ( itr.hasNext() ) { System.out.println( itr.next() ); } // or, in Java 5 ArrayList myArrayList = new ArrayList(); for( Object o : myArrayList ) { System.out.println( o ); } |
vector myVec; for ( vector<int>::iterator itr = myVec.begin(); itr != myVec.end(); ++itr ) { cout << *itr; }
|
String | String (string对象和String对象都可以使用 “+”连接) 区别: 1) String对象无[]操作 2) StringBuider和StringBuffer无“+”连接,使用append连接
| string (string对象和String对象都可以使用 “+”连接) string a, b; a[1] == 'a'; // 得到某个字符 a = b; // 字符串拷贝 a >= b; // 字典序比较 a[1] = b[1]; // 修改某个字符 a += b; // 字符串拼接 a = a + b; // 字符串拼接 a += "123"; // 字符串拼接 a = b + "123"; // 字符串拼接 int len = a.length(); // 字符串的长度 size(s1); (A + A).find(B) != string::npos |
| int hits = Integer.parseInt(str); for (char ch : Integer.toString(count).toCharArray()) newstr = str.toLowerCase(); char c[]=s.toCharArray(); domain.indexOf(" "); domain.substring(0,i); //i是结束下标的后面一个 String d = s.substring(i + 1); counts.put(cur, counts.getOrDefault(cur, 0) + hits); StringBuilder sb = new StringBuilder(); sb.append(sum % 2); result.insert(0, (char)('A' + n % 26)); //StringBuilder result = new StringBuilder(); return sb.reverse().toString(); | int n = stoi(); for (char ch : to_string(count)) for (auto & c: p) c = tolower(c); 不需要 int id = domain.find(" "); domain.substr (0, i); //i是子串长度 s.substr(i + 1); counts [s.substr(i + 1)] += n; string result = ""; result += to_string(sum % 2); //char不用加to_string() char temp = 'A' + n % 26; result = temp + result; //string result = ""; reverse(result.begin(), result.end()); return result;
|
二维数组 | int p[] = new int[m]; //一维 Integer[][] map = new Integer[m][n]; //二维
| int * p = new int[m]; //一维 A** ga = new A*[m]; //二维 for(int i = 0; i < m; i++)
int a[2][3]={{1,2,3},{4,5,6}}; |
不定数组 | ArrayList<Integer> arr=new ArrayList<>(); arr.add(1);//添加 arr.add(2,6); arr.size();//获取长度 arr.set(1, 4);//修改 int st=arr.remove(0);//删除 //arr.clear();//清空 //arr.get(1);//获取 int v=arr.indexOf(3);//获取索引
| vector<int> a, b; a.push_back(1); // 推入一个新的值到数组最后 a.pop_back(); // 删除数组最后的那个值 a.front(); // 数组开头的值 a.back(); // 数组结尾的值 a = b; // 数组拷贝 a == b; // 数组是否相同 a[1]; // 数组中第二个值
vector<int> a; //初始化长度vector<int> ret(intersect.size()); a.size(); // 容器内的元素个数 a.empty(); // 容器是否为空 // 除了queue和stack外通用的方法 a.clear(); // 清空容器内的所有元素 a.begin(); // 容器的一个元素的迭代器 a.end(); // 容器尾后迭代器
vector<int> v; vector<int>::iterator iter // 定义迭代器 iter = v.begin(); // 数组头“指针” iter = v.end(); // 数组尾“指针” reverse(v.begin(), v.end()); reverse(nums.begin(), nums.begin()+k); |
| return new int[]{left + 1, right + 1}; List<String> res = new ArrayList<>(); window = new int[size]; //int[] window; nums.size() | return vector<int>{left + 1, right + 1}; vector<string> res; window.resize(size); //vector<int> window; vector<int>& nums nums.length |
双向链表 | linkedList | list |
| LinkedList 实现 Deque 接口,即能将LinkedList当作双端队列使用。 LinkedList<Integer> lin=new LinkedList<>(); lin.addFirst(st);//在首部加 lin.addLast(st);//在尾 lin.removeFirst();//移除首元素 lin.removeLast();//尾 lin.push(st);//压入栈 lin.pop();//弹出栈 | list<int> l; l.push_front(1); // 插入元素到开头 l.pop_front(); // 从开头删掉元素 l.erase(l.begin()); // 删除指定迭代器处的元素 l.insert(l.begin(), 1); // 在指定迭代器前插入元素 l.reverse(); // 反转整个链表 |
null | null | NULL |
栈 | Stack | stack |
| push(x) - 压入栈 peek() - 就看看,返回值 pop() - 扔掉,返回值 int popItem = stk.pop(); stack.isEmpty() | push(x) - 压入栈 top - 就看看,返回值 pop - 扔掉,不返回值 int popItem = stk.top(); stk.pop(); stack.emtpy() |
队列 | Queue | queue |
| offer - 从队尾添加 peek() - 就看看队首,返回值 poll - 扔掉,返回值 | push - 从队尾添加 front() -就看看队首,返回值 pop - 扔掉,不返回值 |
pair | 没有 | pair (c++) |
|
| #include<map> pair<int, string> p; p.first = 1; p.second = "abc"; p = make_pair(1, "abc"); p = {1, "abc"};
pair<int, string> p[100]; sort(p, p + 100); // 默认优先first从小到大 // 如果first相同则second从小到大 pair与其他结构嵌套: vector<pair<int, string> > vp; queue<pair<float, int> > qp; queue<pair<pair<int, int>, int> > qpp; |
| new int[]{a,b} | make_pair(it->second, it->first) |
set | Set | unordered_set |
| Set<String> ban = new HashSet<>(Arrays.asList(banned)); //String[] banned | unordered_set<string> ban(banned.begin(), banned.end()); //vector<string>& banned |
treeSet | treeSet | set |
| HashSet<Integer> hashset=new HashSet<>(); hashset.add(4);//添加 hashset.remove(2); //找到值2删除 | 内部有序(默认从小到大) 几乎所有操作复杂度均为 O(logN) set<int> s; s.insert(1); // 插入到集合中 s.erase(1); // 从集合中删除 s.erase(s.begin()); // 从集合中删除 s.count(1); // 集合中是否存在 s.find(1); // 返回对应值的迭代器(若无则返回尾后迭代器) |
map | hashMap | unordered_map |
| HashMap<Integer, Integer> map=new HashMap<>(); map.put(1, 1); //添加元素 map.put(1, 2); //替换 map.remove(4); map.get(1); map.size(); System.out.println(map); map.clear(); numMap.put(num, numMap.getOrDefault(num, 0) + 1); numMap.containsKey(key - k) for (auto d : map) res.push_back (to_string(d.second) + " " + d.first); for (int num : map.keySet()){} // Map<Integer, Integer> map = new HashMap<>();
| myUnorderedMap.empty() //检查容器是否为空 myUnorderedMap.size() //返回容纳的元素数 myUnorderedMap.max_size() //返回可容纳的最大元素数 myUnorderedMap.insert({ 0, 100 }); //插入元素 myUnorderedMap.erase(0); //按key删除元素 myUnorderedMap.erase(myUnorderedMap.begin());//按迭代器删除元素 myUnorderedMap.clear(); //清空map numMap[num]++ numMap.find(key - k) != map.end() for (String d : map.keySet()) res.add(map.get(d) + " " + d); for(auto it = map.begin(); it != map.end(); it++){} // unordered_map<int,int> map;
#include <unordered_map> #include <iostream> int main() { std::unordered_map<int, std::string> c = {{1, "one"}, {2, "two"}, {3, "three"}, {4, "four"}, {5, "five"}, {6, "six"}}; // 从 c 擦除所有奇数 for(auto it = c.begin(); it != c.end(); if(it->first % 2 == 1) //it的类型太冗长,因此用auto it = c.erase(it); else ++it; for(auto& p : c) //for each 类型的loop std::cout << p.second << ' '; //当使用iterator时,iterator的first指向key,second指向value } |
| int maxFreq = 0; String ret = ""; for (String str : map.keySet()) { if (map.get(str) > maxFreq) { maxFreq = map.get(str); ret = str; } } | string res; int max_count = 0; for(auto c : count){ if(c.second > max_count){ max_count = c.second; res = c.first; } } |
|
|
|
| treeMap | map |
|
| map是按照key进行排序的; map<char, int> m; m.insert(make_pair('a', 1)); // 加入字典 m.insert({'a', 1}); // 加入字典 m.erase('a'); // 从字典中删除 m.count('a'); // 字典中是否存在 m.find('a'); // 返回对应值的迭代器(若无则返回尾后迭代器) map<int, vector<int>> m; for (auto& [i, v] : m) { …} vector<vector<int>>& items; for (auto& v : items) m[v[0]].push_back(v[1]); |
priority queue | PriorityQueue | priority_queue |
|
| 默认为最大堆,即堆顶的元素最大 插入和弹出操作的复杂度均为O(logN) priority_queue<int> prq; prq.top(); // 堆顶上的元素 prq.pop(); // 弹出堆顶上的元素 prq.push(1); // 推入堆 priority_queue<int, vector<int>, greater<int>> pq; |
sort |
|
|
|
| #include<algorithm>; sort是不稳定排序 bool cmp(int a, int b) { return a > b; } int a[] = {1, 2 ,3 , 4}; sort(a, a + 4, cmp); |
| 需要Priority queue或treeMap | partial_sort(v.begin(), v.begin() + 5, v.end(), greater<int>()); |
| java | c++ |
| double 要用%f; | double 要用%d |
| If , while,for 中进行真假判断时只能使用逻辑表达式,不能用1和0数字来表示真假 | 可以用0和1来表示真假
|
| Math.max(a,b); Math.abs(item); | max(a,b); abs(item); //min,max是保留字 |
| Integer.MAX_VALUE | INT_MAX |
| root.left | root->left |
| // Step 1: remove punctuations and change to lower case; String[] strs = paragraph.toLowerCase().split("\\W+"); | // Step 1: remove punctuations and change to lower case; for(auto &c : paragraph) c = isalpha(c)? tolower(c) : ' '; |
| // Step 2: count the frequency of every word Map<String, Integer> map = new HashMap<>(); for (String str : strs) { if (!set.contains(str)) { map.put(str, map.getOrDefault(str, 0) + 1); } } | // Step 2: count the frequency of every word istringstream iss(paragraph); string lower_word; while(iss >> lower_word) ++count[lower_word]; |
| int freq [] = new int[26]; for(int i = 0; i < s.length(); i++) { freq [s.charAt(i) - 'a'] ++; } | //c++中s.charAt(i) - 'a'不行 unordered_map<char, int> m; for (auto &c : s) { m[c]++; } |
| TreeNode root = new TreeNode(nums[midIdx]); | TreeNode *root = new TreeNode(nums[midIdx]); |
| int[] sFirstOccurIdx = new int[256]; sFirstOccurIdx[s.charAt(i)] = i; | char map_s[128] = { 0 }; map_s[s[i]] = i+1; |
| words[i].equals(word1) | words[i] == word1 |
| row.set(j, row.get(j) + row.get(j-1)); row.add(1); //直接在后面动态加就可以 | r[i].resize(i + 1); //Pascal's Triangle, vector<vector<int>> r(numRows); r[i][0] = r[i][i] = 1; |
| int[] newNumber = new int[digits.length + 1]; // overflow newNumber[0] = 1; | digits[0] =1; digits.push_back(0); |
| 没有 | gcd(size(s1), size(s2)) |
| Arrays.sort(words, (a,b)->a.length()-b.length()); | sort(words.begin(), words.end(), compare); static bool compare(const string &s1, const string &s2) { return s1.length() < s2.length(); } |
|
|
|
source:
https://www.cnblogs.com/enjoy233/p/10408787.html
https://blog.csdn.net/believexfr/article/details/52760234
https://blog.csdn.net/fztsilly/article/details/106409014