C++:将指针向量传递到函数中

c++: passing vector of pointers into a function

本文关键字:函数 向量 指针 C++      更新时间:2023-10-16

在我正在编写的程序中,我有一个指针向量来尝试节省内存使用量,尽管这将使我的程序更有效率,但我在将指针向量传递到函数direct()时遇到了麻烦。非常感谢任何有关将其传递到函数的正确语法的帮助

当前显示的错误是:"错误无法将'std::vector*>'转换为'const string'...对于参数"1"...标记此错误的行是调用函数 direct 的行

#include <iostream>
#include <vector>
using namespace std;
// a function used to display an array used for testing purposes
void display_array(const string *arr, size_t size )
{
    int i;
    for (i = 0; i < size; i++){
       cout<<(int(arr[i][0]))-64;
       cout<<(int(arr[i][1]))-64;
       cout<<",";
    }
}
// Takes in the connections to the start and the connections to the end and returns the connection if
//there is a direct connection else returns 0
string direct(const string *destination, char *start, size_t destination_size) {
    for (int i = 0; i<destination_size;i++)
        if ((&destination[i][0] == start) or (&destination[i][1] == start))
            return destination[i];
}
int main()
{
    string current;
    std::vector<string> paths;
    std::vector<string*> start_connections;
    std::vector<string*> destination_connections;
    char start;
    char destination;
    cout<<"Input paths in the form 'AB'(0 to exit)n";
    cin>>current;
    while (current != "0"){
        paths.push_back(current);
        cin>>current;
    }
    cout<<"Input starting locationn";
    cin>> start;
    cout<<"Input final destinationn";
    cin>>destination;
    for(int i = 0; i < paths.size(); i++) {
        if ((paths[i][0] == destination) or (paths[i][1] == destination))  //all connections to the destination
            destination_connections.push_back(&paths[i]); // paths stored as a pointer to paths array
        if ((paths[i][0] == start) or (paths [i][1] == start)) //all connections to the start
            start_connections.push_back(&paths[i]); // paths stored as a pointer to paths array
    }
    cout<<direct(&destination_connections,&start,destination_connections.size());
    if( !paths.empty() )
      display_array( &paths[0], paths.size() );
}
编译器准确地

告诉你出了什么问题 - 向量不是指针。

理想情况下,你根本不应该使用指针 - 将你的向量声明为

std::vector<std::string>

并传递对使用它的函数的引用

... direct(const std::vector<std::string> & dest, ...)

然后,您只需按值传递向量,但引用运算符告诉编译器只传递其地址而不是整个对象。

您还可以获得不必单独传递其大小的好处,因为遍历它的函数可以直接访问它(尽管通过索引访问它并不是真正的 OO 方式)。

在C++中,如果您使用的是裸指针,则可能做错了;)

您正在尝试传递需要string*vector<string*>*

更改此设置:

direct(&destination_connections, &start, destination_connections.size());

对此:

direct(&destination_connections[0], &start, destination_connections.size());

或者,如果您使用的是 C++11:

direct(destination_connections.data(), &start, destination_connections.size());

话虽如此,or不是有效的C++关键字,则需要改用||。而且我认为您在display()内部处理指针不正确. 你需要对你真正想要完成的事情进行代码审查。