简体   繁体   中英

C++ : Error could not convert from std::vector<int>* to std::vector<std::vector<int> >

I want to use vector<int> adj[] as my parameter and vector<vector<int>> as my return function type but doing that will cause an error: This happens when returning the vector adj.

could not convert adj from std::vector<int>* to std::vector<std::vector<int> >
          return adj;

How can I solve this issue?

This is my program:

  vector<vector<int>>printGraph(int V, vector<int> adj[])
        {
             for ( int i = 0 ; i < V ; i ++)
             {
                for (auto x : adj[i])
                cout << x;
                cout<<"\n";
             }
             
             return adj;
        }

As I got your are trying to convert the array of vectors to a vector of vectors. Try to return an interval of elements of the original array.

return { adj, adj + V };

I realized you are unnecessarily returning adj, if you just want to print you can do yourself a favor and use a void function instead check this code out:

#include <iostream>
#include <vector>

using namespace std;

void printGraph(int V, vector<int> adj[])
{
    for (int i = 0; i < V; i++) {
        for (auto x : adj[i]) {
            cout << x << endl;
        }
    }
}

int main()
{
    vector<int> cat{ 1, 2, 3, 4 };
    vector<int> arr[4] = { cat, cat, cat, cat };
    printGraph(4, arr);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM