java和c++语法对比列表

1 篇文章 0 订阅

                                                                                    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)

print

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++) 
    ga[i] = new A[n]; 
    ... 
for(int i = 0; i < m; i++) 
    delete []ga[i]; 
    delete []ga; 

 

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();                      // 容器是否

// 除了queuestack外通用的方法

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 行真假判断只能使用逻辑表达式,不能用10数字来表示真假

可以用01来表示真假

 

 

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

 

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值