c++ - vector 问题的 vector

标签 c++ list stl vector

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

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

最佳答案

改变

 (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 );

关于c++ - vector 问题的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8222995/

相关文章:

c++ - 使用元素键迭代 STL 容器

c++ - 当短路禁用其评估时,正在读取常量表达式中允许的尾数指针

python - 合并列表中的重叠项目

c++ - 使用 Gurobi 向模型添加约束时出现问题

java - Try-catch-finally 从 Java 到 C++

c++ - `int` 假定在 OpenCV 中始终为 32 位?

python - 如何为 Python 列表切片返回任何内容

java - ArrayList 改变所有对象的一个​​属性值

c++ - 如何在具有非常量指针键的映射中通过常量指针键查找

c++ - std::map::size() 不同于迭代器