c++基礎語法學習

最近要參加各個學校的夏令營,夏令營要有機試,這很多學校只讓用c++,奈何我只會寫java,所以來學些c++的基礎語法,但願能通過夏令營吧。。。。

  1. 字符串的拼接:
#include <iostream>
#include<sstream>
using namespace std;

int main(int argc, char** argv) {
	stringstream ssm;
	ssm<<1<<"abc";
	cout<<ssm.str()<<endl;
	return 0;
}
  1. vector在開頭插入
    vector<string> words;
    words.push_back("hahah");//結尾插入
    vector<string>::iterator iter;
    iter=words.begin();
    words.insert(iter,"gaga");//開頭插入
  1. 在方法中改變參數的值
    一般來說,方法中是不能修改全局變量的值的,因爲方法在堆裏面執行,全局變量保存在棧裏面,執行時從棧中複製一份傳給堆。但是我們可以通過指針,將棧裏面的變量地址傳給方法,這樣方法就可以修改變量的值了。

比方說,這樣是不能改變變量的值:

vector<string> change(vector<string> words){
    words[0]="haha";
    return words;
}

int main(int argc, char** argv){
    vector<string> words;
    words.push_back("gaga");
    change(words);
    for(int i=0;i<words.size();i++){
        cout<<words[i]<<endl;
    }
    return 0;
}

但是這樣是可以改變vector的值:

vector<string> change(vector<string>& words){
    words[0]="haha";
    return words;
}

int main(int argc, char** argv){
    vector<string> words;
    words.push_back("gaga");
    change(words);
    for(int i=0;i<words.size();i++){
        cout<<words[i]<<endl;
    }
    return 0;
}
  1. 遍歷STL的集合類
//vector
for(vector<int>::iterator iter=nums.begin();iter!=nums.end();iter++){
            cout<<*iter<<endl;
}

//map
for(map<int,int>::iterator iter=map1.begin();iter!=map1.end();iter++){
            cout<<iter->first<<endl;
            cout<<iter->second<<endl;
}
  1. 自定義sort排序函數
    使用sort函數需要在頭文件引入
#include<algorithm>

自定義排序函數的實現:

vector<int> sortByBits(vector<int>& arr) {
        sort(arr.begin(),arr.end(),cmp);
        return arr;
    }

    static bool cmp(int x1,int x2){
        int y1=getNum(x1);
        int y2=getNum(x2);
        if (y1==y2){
            return x1<x2;
        }else{
            return y1<y2;
        }
    }

    static int getNum(int x){
        int count1=0;
        cout<<"X:"<<x<<endl;
        while(x>0){
            count1+=x%2;
            x/=2;
        }
        cout<<count1<<endl;
        return count1;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章