為什麼當我用 stl 向量替換數組時,我的代碼會變慢,在 C++ 中,數組是否比向量更快?

非洲國王

下面是我用來比較的代碼:

// Example program
#include <iostream>
#include <string>
#include <vector>
#include <chrono>
using namespace std::chrono;
using namespace std;
            
bool existHelperArrayVersion(string &word, int i, int u_i, int u_j, vector<vector<char>>& Board)
{
    if(i>=word.length())
    {
        return true;
    }
    else
    {
        bool answer  = false;      
        if(Board[u_i][u_j] == word[i])
        {
            char temp             = Board[u_i][u_j];
            Board[u_i][u_j]       = '?';
            int row_len           = Board.size();  
            int col_len           = Board[0].size();

            // Uses Array
            int row_offset[4]={0,  0, 1, -1};
            int col_offset[4]={1, -1, 0,  0};
            
            for(int k=0; k<4; k++)
            {
                int v_i = u_i + row_offset[k];
                int v_j = u_j + col_offset[k];
                
                if( !(0 >v_i || v_i >= row_len || 0>v_j || v_j >= col_len)  && (Board[v_i][v_j] != '?'))
                    answer |= existHelperArrayVersion(word, i+1, v_i, v_j, Board);
            }
               
            if(i+1 == word.length())
                answer |= true;
            Board[u_i][u_j] = temp;
        }
        return answer;
    }
}

bool existHelperVectorVersion(string &word, int i, int u_i, int u_j, vector<vector<char>>& Board)
{
    if(i>=word.length())
    {
        return true;
    }
    else
    {
        bool answer  = false;
        if(Board[u_i][u_j] == word[i])
        {
            char temp             = Board[u_i][u_j];
            Board[u_i][u_j]       = '?';
            int row_len           = Board.size();  
            int col_len           = Board[0].size();

            //Uses Vectors
            vector<int> row_offset = {0,  0, 1, -1};
            vector<int> col_offset = {1, -1, 0,  0};
            
            for(int k=0; k<4; k++)
            {
                int v_i = u_i + row_offset[k];
                int v_j = u_j + col_offset[k];
                
                if( !(0 >v_i || v_i >= row_len || 0>v_j || v_j >= col_len)  && (Board[v_i][v_j] != '?'))
                    answer |= existHelperVectorVersion(word, i+1, v_i, v_j, Board);
            }
               
            if(i+1 == word.length())
                answer |= true;
            Board[u_i][u_j] = temp;
        }
        return answer;
    }
}

bool exist(vector<vector<char>>& board, string word, int option) 
{
    if(option == 0)
        cout << "----ARRAY------\n";
    else if(option == 1)
        cout << "---VECTOR-----\n";
        
    bool answer   = false;
    for(int i=0; i<board.size(); i++)
    {
        for(int j=0; j<board[i].size(); j++)
        {
            if(option == 0)
                answer |= existHelperArrayVersion( word, 0, i, j, board);
            else if(option == 1)
                answer |= existHelperVectorVersion( word, 0, i, j, board);
                
            if(answer)
            {
                return true;
            }
        }
    }
    return false;
}

int main()
{
    
    string word                 =   "AAAAAAAAAAAAAAB";
    vector<vector<char>> board  =   {{'A','A','A','A','A','A'},
                                     {'A','A','A','A','A','A'},
                                     {'A','A','A','A','A','A'},
                                     {'A','A','A','A','A','A'},
                                     {'A','A','A','A','A','A'},
                                     {'A','A','A','A','A','A'}};

    auto start    = high_resolution_clock::now();
    bool answer   = exist(board, word, 0);
    auto stop     = high_resolution_clock::now();
    auto duration = duration_cast<microseconds>(stop - start);
    cout << "Time taken when Using C-style Array : " << duration.count() << " microseconds" << endl;
    
    start         = high_resolution_clock::now();
    answer        = exist(board, word, 1);
    stop          = high_resolution_clock::now();
    duration      = duration_cast<microseconds>(stop - start);
    cout << "Time taken when Using STL vector    : " << duration.count() << " microseconds" << endl;
    
}

輸出

----ARRAY------
Time taken when Using C-style Array : 112931 microseconds
---VECTOR-----
Time taken when Using STL vector    : 330641 microseconds

如您所見,我的函數的數組版本的執行速度平均比其 Vector 版本快 3 倍。(我多次運行並得到了類似的結果)
問:
與數組相比,向量真的那麼慢嗎?
我認為他們的表現應該是相提並論的。
這是我在在線環境中運行的 URL http://cpp.sh/6x22b

Yakk - Adam Nevraumont
        vector<int> row_offset = {0,  0, 1, -1};
        vector<int> col_offset = {1, -1, 0,  0};

每次調用該函數時,這都會導致 2 堆數據分配(幾乎)。

        int row_offset[4]={0,  0, 1, -1};
        int col_offset[4]={1, -1, 0,  0};

每次調用該函數時,這不會(幾乎)導致 2 堆數據分配。

std::vector<int> foo = {1,2,3}類似於int* foo = new int[]{1,2,3},而不是int foo[] = {1,2,3}創建成本。

std::array<int, 3> foo={1,2,3}

是“帶有數據的固定大小緩衝區”的標準庫版本。std::vector是一個動態大小的緩衝區。

是一個實時示例,我交換std::vectorstd::array,並更改了 C 數組版本以動態創建和銷毀數組。你會注意到時間交換。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

C ++:STL排序STL数组的STL向量

為什麼我的數據庫中會出現空數組?

為什麼 .includes() 不適用於我的對像數組?

Xamarin/C# - 在日期範圍內查找周末的方法。為什麼我卡在循環中並且無法增加當前日期?

為什麼當我有 0x00 時我的數據被剪切?

為什麼我的函數返回 0.0?(C 代碼)

為什麼當數據類型匹配時外鍵會給我一個錯誤

為什麼 VS 為我的析構函數標記 C26432?

我們什麼時候在 C++ 中使用數組而不是向量,反之亦然?

當我嘗試將“glfwSetErrorCallback”函數放入 cout 時,為什麼會得到整數輸出,該函數返回非整數值?

為什麼當我將變量放在帶有 + 操作數的向量中時我的代碼不起作用

為什麼我在 C 中的 main 函數只打印第一個 for 循環?

為什麼向量比數組好?

為什麼我用shuffle方法得到一個重複的數組

當複制構造函數在 C++ 中不可用時,為什麼不調用複制賦值運算符?

為什麼當我運行 javascript 函數時我的 RAM 會超載?

為什麼這些比較在 C 中在數學上相同時會給我不同的答案?

為什麼我的 C 數組會記住之前函數調用的舊數據?

為什麼當我使用指針將數組傳遞給函數時,數組的長度顯示為 1?

為什麼我的數組中的這些整數值會發生變化?

為什麼當我將 Pandas 數據框用作具有多處理功能的函數的輸入時它不會改變

為什麼使用 jQuery 函數的按鈕沒有用類隱藏我的 div:.red、.yellow - 當我點擊它時?

我的 C 函數反轉數組在連續運行後用隨機數填充第一個和最後一個索引。為什麼是這樣?

為什麼當我將數據發送到我的 firebase 時我的 android studio 應用程序崩潰

為什麼我的代碼調用一個函數兩次?

當我向數組添加新項目時,為什麼我的列表沒有更新?

我在數組中的 c++ 中的二進制搜索功能不起作用,我不明白為什麼

為什麼當我嘗試重新分配()結構的指針數組時,我的 C 程序會崩潰?

當我嘗試將它添加到數組時,為什麼我的對像被複製?