【问题标题】:A vector of vector problems向量问题的向量
【发布时间】:2011-11-22 06:45:58
【问题描述】:

我正在尝试遍历字符串列表并查找给定字符在所述字符串中的位置。然后,我根据字符出现的位置/是否将字符串存储在给定的向量中。在循环完成执行之前,我在以下代码中遇到运行时错误。我已经检查了六次,似乎找不到任何问题。

vector< vector<string> > p;
for(list< string >::iterator ix = dictionary.begin(); ix != dictionary.end(); ix++)
{
    int index = contains(*ix, guess);
    index++;

    p.at(index).push_back(*ix); //0 will contain all the words that do not contain the letter
                                //1 will be the words that start with the char
                                //2 will be the words that contain the the char as the second letter
                                //etc...
}



int contains(string str, char c)
{
    char *a = (char *)str.c_str();
    for(int i = 0; i < (str.size() + 1); i++)
    {
        if(a[i] == c)
            return i;
    }
    return -1;
}

【问题讨论】:

    标签: c++ list stl vector


    【解决方案1】:

    改变

     (str.size() + 1)
    

    ...到

     str.size()
    

    你将在 str.size() 处处于未定义的领域,更不用说那个 PLUS 了。

    就此而言,您为什么要摆弄额外的 char* 而不是 std::string[]?

    对于那个问题,你为什么不简单地使用std::string::find()

    当然,假设您使用的是 std::string 而不是其他字符串... :)

    实际上,回到调用站点... string::find() 返回目标字符匹配的索引,如果不匹配,则返回 string::npos。那么,你能完全省掉额外的功能吗?

     int pos = (*ix).find( guess );
     p.at( (  pos == string::npos ) ? 0 : ( pos + 1 ) ).push_back( *ix );
    

    【讨论】:

    • 而且,正如这里的其他人所指出的那样,您确实应该在尝试查看 p 之前填充它。
    【解决方案2】:

    vector p 将 p 定义为空向量。在使用 vector::at() 之前,您必须添加矢量元素。 例如:

    const size_t MAX_LETTERS_IN_WORD = 30;
    vector< vector<string> > p(MAX_LETTERS_IN_WORD);
    
    /* same as before */
    

    作为替代方案,您可以根据需要在使用 at() 和 push_back() 将其他元素放入 p 之前检查 p.size()

    【讨论】:

      【解决方案3】:

      运行时错误的问题,可能是因为您访问向量p 在一个尚不存在的位置。在访问特定索引之前,您必须在向量中腾出空间。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-09
        • 1970-01-01
        • 2022-01-24
        • 2011-06-09
        • 1970-01-01
        • 2010-10-16
        相关资源
        最近更新 更多