首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向量问题的向量

向量问题的向量
EN

Stack Overflow用户
提问于 2011-11-22 14:45:58
回答 3查看 211关注 0票数 0

我正在尝试遍历一个字符串列表,找出给定字符在所述字符串中的位置。然后,我根据字符出现的位置/情况将字符串存储在给定的向量中。在执行完循环之前,我在下面的代码中得到了一个运行时错误。我已经检查过它六次了,似乎没有发现任何问题。

代码语言:javascript
复制
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;
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-11-22 15:03:03

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

代码语言:javascript
复制
const size_t MAX_LETTERS_IN_WORD = 30;
vector< vector<string> > p(MAX_LETTERS_IN_WORD);

/* same as before */

作为另一种选择,您可以在使用at()和push_back()之前先检查p.size(),根据需要将其他元素添加到p中

票数 2
EN

Stack Overflow用户

发布于 2011-11-22 14:51:37

变化

代码语言:javascript
复制
 (str.size() + 1)

...to

代码语言:javascript
复制
 str.size()

在str.size()中,您将处于未定义的领域,更不用说加1了。

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

就此而言,为什么不简单地使用std::string::find()

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

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

代码语言:javascript
复制
 int pos = (*ix).find( guess );
 p.at( (  pos == string::npos ) ? 0 : ( pos + 1 ) ).push_back( *ix );
票数 5
EN

Stack Overflow用户

发布于 2011-11-22 15:06:08

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8222995

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档