Reputation: 41
I am making a program that will take in a text and:
But I'm having a problem when I try to compare a string against a struct string member. I get vector out of range. Please review the code below. Hope someone can tell me what i am doing wrong
#include <iostream>
#include<string>
#include <vector>
using namespace std;
struct word_entry {
string word;
int amount;
} ;
typedef vector<word_entry> type_of_vector;
void insert(type_of_vector word_storage,string word_to_insert)
{
bool word_found =false;
for(int i = 0;i<=word_storage.size();i++)
{
if(word_storage.at(i).word==word_to_insert) //crashes the program
{
word_storage.at(i).amount++;
word_found=true;
}
}
}
int main()
{
type_of_vector word_vector;
string word_to_insert="kalle";
word_entry insert_word={word_to_insert,1};
word_vector.insert(word_vector.end(),insert_word);
insert(word_vector,word_to_insert);
}
Upvotes: 1
Views: 112
Reputation: 310990
This for statement
for(int i = 0;i<=word_storage.size();i++)
gives you the exception because index equal to szie() is invalid. The valid range for indexes is [0, size() - 1] provided that the vector is not empty.
Instead of the loop you could use standard algorithm std::find_if. For example
void insert(type_of_vector &word_storage, const string &word_to_insert)
{
auto it = std::find_if( word_storage.begin(), word_storage.end(),
[&]( const word_entry &entry ) { return ( entry.word == word_to_insert ); } );
if( it != word_storage.end() )
{
it->amount++;
}
}
Upvotes: 0
Reputation: 49986
Few hints:
using namespace std;
dont include whole std
namespace in your project
void insert(type_of_vector word_storage,string word_to_insert)
word_storage will always be a copy of what your have put in the function call, if you dont want a copy (and it looks like you dont) use reference type_of_vector& word_storage
. Also it makes sense to use const string& word_to_insert
, if word_to_insert is not supposed to change.
for(int i = 0;i<=word_storage.size();i++)
you are iterating out of bounds, use <
compare rather than <=
Upvotes: 4
Reputation: 4813
It has to be
for(int i = 0; i < word_storage.size();i++)
Use "less than" '<' instead of "less than or equal" '<='.
Upvotes: 5