0

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?

4

2 に答える 2

2

イテレータはおそらく無効です。それ以外の場合は、ある文字列を別の文字列に割り当てる際に問題になることはありません。

1 つの問題は次の行です。

str1.erase(is);

これは無効isになります。おそらく次のように変更する必要があります。

is = str1.erase(is);

とはどういう意味ivですか? 次のようなものを追加する必要があるようです。

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

同じように。

于 2012-04-18T11:28:48.337 に答える
1

イテレータまたはベクトルのスペースの割り当てに問題があると思います。これが機能するはずです

#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;
}
于 2012-04-18T11:43:26.377 に答える