передача вектора в функцию с ++ - PullRequest
5 голосов
/ 06 октября 2011

У меня есть main.cpp test.h и test.cpp> Я пытаюсь передать свой вектор, чтобы я мог использовать его в test.cpp, но продолжаю получать ошибки.

   //file: main.cpp
    int main(){
        vector <Item *> s;
         //loading my file and assign s[i]->name and s[i]-address
         tester(s);
    }

    //file: test.h
    #ifndef TEST_H
    #define TEST_H
    struct Item{
        string name;
        string address;
    };
    #endif

    //file: test.cpp
    int tester(Item *s[]){
        for (i=0; i<s.sizeof();i++){
            cout<< s[i]->name<<"  "<< s[i]->address<<endl;
        }
        return 0;
    }



    ---------------errors--------
    In file included from main.cpp:13:
    test.h:5: error: âstringâ does not name a type
    test.h:6: error: âstringâ does not name a type
    main.cpp: In function âint main()â:
    main.cpp:28: error: cannot convert âstd::vector<Item*, std::allocator<Item*> >â to âItem**â for argument â1â to âint tester(Item**)â

Ответы [ 6 ]

13 голосов
/ 06 октября 2011

A std::vector<T> и T* [] не являются совместимыми типами.

Измените сигнатуру tester() функции следующим образом:

//file: test.cpp
int tester(const std::vector<Item>& s)   // take a const-reference to the std::vector
                                         // since you don't need to change the values 
                                         // in this function
{
    for (size_t i = 0; i < s.size(); ++i){
        cout<< s[i]->name<<"  "<< s[i]->address<<endl;
    }
    return 0;
}

Существует несколько способов передать это std::vector<T> и все имеют немного разные значения:

// This would create a COPY of the vector
// that would be local to this function's scope
void tester(std::vector<Item*>); 

// This would use a reference to the vector
// this reference could be modified in the
// tester function
// This does NOT involve a second copy of the vector
void tester(std::vector<Item*>&);

// This would use a const-reference to the vector
// this reference could NOT be modified in the
// tester function
// This does NOT involve a second copy of the vector
void tester(const std::vector<Item*>&);

// This would use a pointer to the vector
// This does NOT involve a second copy of the vector
// caveat:  use of raw pointers can be dangerous and 
// should be avoided for non-trivial cases if possible
void tester(std::vector<Item*>*);
2 голосов
/ 06 октября 2011
  1. Вы должны #include <string>.
  2. string name следует читать std::string name и т. Д. То же самое относится к std::vector.
  3. Вы звоните tester() с vector, но он ожидает массив (оба не являются взаимозаменяемыми).
  4. s.sizeof() неверно как для массива, так и для вектора; для последнего используйте s.size() или, еще лучше, используйте итератор.

Это просто ошибки, которые сразу же выпрыгивают; может быть больше.

2 голосов
/ 06 октября 2011

Передайте его как std::vector<Item *> & (ссылка на вектор) и используйте итератор для его итерации.

1 голос
/ 06 октября 2011

A vector не является массивом.

int tester(vector<Item *> &s)

(передать как ссылку, чтобы избежать копирования или если вам нужно изменить)

Вам также необходимо изменить код внутри функции tester, чтобы он работал корректно как вектор.

0 голосов
/ 06 октября 2011

Вам не хватает включает

#include <string>
#include <vector>

и вам нужно использовать std::string и std::vector<>. std::vector не является массивом, поэтому вы должны передать вектор как ссылку

int tester(std::vector<Item*> & vec) { //... }

или даже как const std::vector<Item*> &, если вы не собираетесь изменять переданный вектор.

Кроме того, вы уверены, что вам понадобится вектор указателей? Чего ты пытаешься достичь?

0 голосов
/ 06 октября 2011

Сначала вы должны исправить

test.h:5: error: âstringâ does not name a type

, вероятно, на using namespace std; и #include <string>

...