簡體   English   中英

錯誤:無法轉換std :: vector <std::basic_string<char> &gt;到std :: string *

[英]error: cannot convert std::vector<std::basic_string<char> > to std::string*

作為C ++的新手,我試圖在我的一個程序中創建一個簡單的void函數來顯示一個數組。 但是標題中有錯誤。 我認為這是一個問題,我試圖用一個不同於函數參數的數組調用它。 我不確定如何修改它。

#include <iostream>
#include <vector>

using namespace std;

void display_array(string arr[]){
    int i;
    for (i = 0; i < sizeof(arr); i++);
        cout<<arr[i];
}

int main()
{
    string current;
    std::vector<string> paths;

    cout<<"Input paths in the form 'AB'(0 to exit)";
    cin>>current;
    while (current != "0"){
        paths.push_back(current);
        cin>>current;
    }
    display_array(paths);
}

任何幫助表示贊賞。

問題是函數display_array接受一個string[]作為參數,但是你傳入一個std::vector<std::string> 您可以通過更改display_array函數來接受對字符串向量而不是數組的const引用來解決此問題:

void display_array(const std::vector<string>& arr) {
    for (auto it = arr.begin(); it != arr.end(); it++)
        cout<<*it;
}

我們將const-reference傳遞給向量而不是傳遞值的原因是我們不會改變向量而我們不想復制它。 盡可能使用const並考慮復制參數的成本是一種好習慣。

在C ++出現之前,函數display_array的符號存在於C中,並且由於C ++與C向后兼容,因此它也在C ++中編譯。

不幸的是,這是相當危險的,因為直覺上,它會導致初學者像你一樣犯錯誤。

實際上你可以用[] fpr替換函數中的指針,這樣它就需要字符串*。 並且大小也是指針的大小,而不是數組中未傳入的元素數。

你的選擇是傳入指針和大小,或者在最后一個是“一個超過序列結束”的范圍內的兩個指針。

如果您使用的是C ++ 03,則必須使用&arr[0]來獲取第一個元素。 在C ++ 11中,你有arr.data()作為方法,當向量為空時也可以安全地調用。 (如果向量為空,技術上&arr[0]是未定義的行為,即使您從未嘗試取消引用此指針)。

因此,一個允許您的代碼在C ++ 03中工作的更正:

void display_array(const string *arr, size_t size )
{
    int i;
    for (i = 0; i < size; i++) // no semicolon here..
       cout<<arr[i];
}

並稱之為:

if( !paths.empty() )
      display_array( &paths[0], paths.size() );

display_array函數接受一個數組,應該帶一個std :: vector

void display_array(std::vector<string> arr) {
    for (auto s : arr)
        std::cout << s;
}

您應該將您的功能簽名編輯為:

void display_array(vector<string> &arr)

和:

for (i = 0; i < arr.size(); i++)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM