Consider the following piece of code.
vector<WordAndLineNumbers>::iterator iter = find(unique_words.begin(),
unique_words.end(), str);
if (iter != unique_words.end())
iter->insert(cur_line_number);
Can these three lines be combined ?
Yes, but only if you make a "null object" and put it at the end of your
unique_words vector. The null object is designed to always end up at the
end of the unique words list when sorted, and it is set up to ignore the
insert. Something like this for example:
class WordAndLineNumbers
{
string _word;
int lineNumber;
public:
WordAndLineNumbers(): _word(), lineNumber() { }
WordAndLineNumbers( string s ): _word( s ), lineNumber() { }
void insert( int n ) {
if ( _word != "" )
lineNumber = n;
}
string word() const { return _word; }
};
bool operator<( const WordAndLineNumbers& lhs,
const WordAndLineNumbers& rhs )
{
if ( lhs.word() == "" ) return false;
else if ( rhs.word() == "" ) return true;
else
return lhs.word() < rhs.word();
}
bool operator==( const WordAndLineNumbers& lhs,
const WordAndLineNumbers& rhs )
{
return lhs.word() == rhs.word();
}
bool operator==( const WordAndLineNumbers& w, const string& s )
{
if ( w.word() == "" ) return true;
return w.word() == s;
}
int main()
{
vector<WordAndLineNumbers> unique_words;
unique_words.push_back( WordAndLineNumbers() );
unique_words.push_back( WordAndLineNumbers( "goodby" ) );
string str = "hello";
int cur_line_number = 3;
sort( unique_words.begin(), unique_words.end() );
unique( unique_words.begin(), unique_words.end() );
assert( find( unique_words.begin(), unique_words.end(), str ) !=
unique_words.end() );
find( unique_words.begin(), unique_words.end(), str )->
insert( cur_line_number );
}