为什么矢量会发生这种情况

时间:2019-06-13 13:57:07

标签: c++ vector

我一直在编写代码以将书添加到库中。当我将书添加到库中并尝试显示它时,库中什么都没有存储(显示)

在这里,我将图书馆最多可容纳100本书。
    int maxbooks = 100;     向量图书馆(maxbooks);   当我删除“(maxbooks)”时,代码工作正常。但是我不   明白为什么吗?

#include <iostream>
#include <vector> 
#include <string>

using namespace std;

//struct model a book 
    struct book {
    string authorname;
    string bookname;
}; //struct ends here 

//function to display number of books in the library
void displayLibrary(vector <book> &cmini_library,int cnum_of_books);

//function to add books to the library;
void add (vector <book> &cminilibrary,book dummylibrary,int &num_of_books);

int main() {
    int option;
    int curr_num_of_books = 0; //current number of books in the library
    int maxbooks = 100; //max number of books our library can hold 
    vector<book> minilibrary(maxbooks); //minilibrary vector of max capacity 100
    book dummylibrary; // a variable used to hold entries for a short period 

    cout << "1.Display all books in the library" << endl;
    cout << "2.Add a book to the library" << endl;
    cout << "option entered: " << endl;
    cin >> option;

    switch (option) {
        case 2:
            add (minilibrary,dummylibrary,curr_num_of_books);
            displayLibrary(minilibrary,curr_num_of_books);
            break;
        }

    return 0;
}

void displayLibrary(vector <book> &cmini_library,int cnum_of_books)
{
    for(int i=0;i<cnum_of_books;i++) {
        cout << "Book name: \t" << cmini_library[i].bookname << endl;
        cout << "Author: \t" << cmini_library[i].authorname << endl;
    }
}

void add(vector<book> &cmini_library,book dummylibrary, int &num_of_books) 
{
    int booksadded=0; // number of books added to the library
    cout << "How many books do you wish to add: ";
    cin >> booksadded;
    cin.ignore(1,'\n');
    for(int i=0;i<booksadded;i++) {
        cout << "Book name: ";
        getline(cin,dummylibrary.bookname); 
        cout << endl;
        cout << "Author: ";
        getline(cin,dummylibrary.authorname);
        cout << endl;
        cmini_library.push_back(dummylibrary);
    }

    num_of_books = num_of_books + booksadded;
}

3 个答案:

答案 0 :(得分:5)

int maxbooks=100;
vector <book> minilibrary(maxbooks);

这些行创建了包含100本书的向量,每本书都是默认构造函数创建的。

现在,当您将新书添加到矢量中时,其大小为101,但是displayLibrary将1作为要打印的书数,然后打印minilibrary[0]-默认为 图书,而不是您添加的图书,即minilibrary[100]

您应该将minilibrary创建为空向量。然后,您可以将书推入其中。

答案 1 :(得分:2)

因为vector<book> minilibrary(maxbooks);创建的图书馆有100个已插入的元素。然后,您尝试显示它们,但是您对插入的元素num_of_books使用了不同的计数器。例如,您添加一本书,现在有101本书,然后打印一本书(第一本),该书为空。添加的图书的索引为100(在最初添加的100之后)。

您可能想要:

vector<book> minilibrary;
minilibrary.reserve(maxbooks);

编辑(我要添加自己的评论以提高其可见性): 整个问题始于不遵守主要规则:不惜一切代价避免冗余。一方面,您将图书数量保持为num_of_books变量,另一方面-minilibrary包含所有图书。如果您跳过num_of_books的值并使用minilibrary.size(),该问题将立即可见-您将获得100本输入的“空”(未初始化)书籍和最后一本书。

答案 2 :(得分:1)

向量类似于数组,但是区别在于它们可以动态调整大小。这就是为什么与数组不同的是,您可以在不指定向量最大限制的情况下初始化向量(在您的情况下为maxbooks)

有关如何以多种方式初始化向量的信息,请参考documentation