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

独自空忆成欢 提交于 2019-12-25 05:12:46

问题


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?


回答1:


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.




回答2:


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;
}


来源:https://stackoverflow.com/questions/10208367/c-how-to-insert-data-to-a-struct-member-struct-located-in-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!