简体   繁体   中英

C++ return vector, can't figure out what's wrong

The following program keeps crashing and I can't figure out what's wrong. It seems that v is somehow not available in the main function..

#include <iostream>
#include <vector>

using namespace std;

vector<string> *asdf()
{
    vector<string> *v = new vector<string>();
    v->push_back("blah");
    v->push_back("asdf");
    return v;
}

int main()
{
    vector<string> *v = NULL;
    v = asdf();

    for (int i=0; i<(v->size()); v++) {
        cout << (*v)[i] << endl;
    }

    delete v;

    return 0;
}

You want:

 for (int i=0; i<(v->size()); i++) {

Your code is incrementing the pointer, not the index. which is a good reason to avoid dynamically allocating things, wherever possible.

您应该将v ++更改为i ++

v ++是原因

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