C++ vector和unordered_map淺析


C++內置的數組支持容器的機制,可是它不支持容器抽象的語義。要解決此問題我們自己實現這種類。在標准C++中,用容器向量(vector)實現。容器向量也是一個類模板。可以說vector的引入,方便了我們對一系列數據的處理,相比於數組,我們不用考慮下標越界等溢出問題了。

使用vecor,需要引入頭文件#include <vector>,命名空間需要引入using std::vector,再補充一下,vector是連續存儲的!!!

簡單的存儲操作:

vector<int> v1;
for (vector<int>::size_type i = 0; i < 10; i++) {
    v1.push_back(i);
}
    cout << "adjective:";
    for (vector<int>::size_type i = 0; i < 10; i++) {
    cout << v1[i] << setw(4);
}

然后比較坑的這個,注意一下就OK了:

//v1中有n個值為i的元素
vector<int> v1(n,i);
//v2中只有n和i兩個元素
vector<int> v2({n,i});

切記我們初始化的時候不能直接v1[i]=value,只能使用v1.push_back(i);

詳細的介紹請看https://www.cnblogs.com/mengfanrong/p/3770971.html

再簡單介紹下unordered_map

C++ 11標准中加入了unordered系列的容器。unordered_map記錄元素的hash值,根據hash值判斷元素是否相同。map相當於java中的TreeMap,unordered_map相當於HashMap。無論從查找、插入上來說,unordered_map的效率都優於hash_map,更優於map;而空間復雜度方面,hash_map最低,unordered_map次之,map最大。

需要引入的頭文件#include <unordered_map>,命名空間需要引入using std::unordered_map,我的理解把他記做鍵值對,即(key,value),很多場合都用到的,比如我們文件管理系統中的頁表索引等等;參考https://www.cnblogs.com/evidd/p/8823092.html

來看一個兩數和的算法吧

//兩數和問題
#include <iostream>
#include <unordered_map>
#include <vector>
#include <iomanip>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::unordered_map;
using std::setw;
class Change {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        unordered_map<int, int> hash;
        for (int i = 0; i < nums.size(); i++) {
            //記錄待查值,接下來搜索
            int another = target - nums[i];
            if (hash.count(another)) {
                //res記錄下標,從0開始的,剛開始我也沒反應過來
                res = vector<int>({ hash[another],i });
                break;
            }
            hash[nums[i]] = i;
        }
        cout << nums[res[0]] << setw(2) << nums[res[1]] << endl;
        return res;
    }
};
int main(int argc, char* argv[]) {
    vector<int> array;
    for (vector<int>::size_type i = 0; i < 5; i++) {
        array.push_back(i + 1);
    }
    int target = 6;
    Change c;
    vector<int> change;
    change = c.twoSum(array, target);
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM