错误:无法转换std :: vector <std :: basic_string <char>&gt;到std :: string * </std :: basic_string <char>

时间:2015-01-13 10:38:36

标签: c++

成为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);
}

感谢任何帮助。

4 个答案:

答案 0 :(得分:4)

问题是函数display_arraystring[]作为参数,但您传递的是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并考虑复制参数的成本。

答案 1 :(得分:0)

在C ++出现之前C中存在函数display_array的符号,并且由于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() );

答案 2 :(得分:0)

display_array函数接受一个数组,应该采用std :: vector

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

答案 3 :(得分:-2)

您应该将您的功能签名编辑为:

void display_array(vector<string> &arr)

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