简体   繁体   中英

c++: how to insert data to a struct member (struct located in vector)

as you could see in the title, I am working on a vector of structs.

one of the struct members is string word . when i am trying to enter data to this member in this way: (*iv).word=temp_str; , i get a runtime error.

while (is!=str1.end())
{
    if (((*is)!='-')&&((*is)!='.')&&((*is)!=',')&&((*is)!=';')&&((*is)!='?')&&((*is)!='!')&&((*is)!=':'))
    {
        temp_str.push_back(*is);
        ++is;
    }
    else
    {        
        (*iv).word=temp_str;
        ++iv;
        str1.erase(is);
        temp_str.clear();
    }
}

this may be the relevant code interval.

should say- word and temp_str are of string type. iv is an iterator to the vector.

what is the right way to enter data into a struct member in this case?

Your iterator is probably invalid, otherwise it shouldn't be a problem assigning one string to another.

One problem is the line:

str1.erase(is);

This will invalidate is , you should probably change it to:

is = str1.erase(is);

What does iv point at? It seems like you would need to add something like:

while (is!=str1.end() && iv != something.end())

as well.

I would guess it is a problem with the iterator or allocating space for the vector. Here is what should work

#define N 10

struct myStruct
{
    int a;
    std::string str;
};

int main()
{
    std::vector<myStruct>  myVector;
    myVector.resize(N); 
    std::vector<myStruct>::iterator itr;    
    for (itr = myVector.begin(); itr != myVector.end(); ++itr)
    {
        std::string tmp = getString();
        itr->str = tmp;
    }
    return 0;
}

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