Reputation: 17
match give_word(
const vector< vector<string> > * source_words,
const vector< vector<string> > * target_words, ...)
{
string synonym1, synonym2;
...
// choose synonyms (if available)
synonym1=source_words[index][rand()%source_words[index].size()];
synonym2=target_words[index][rand()%target_words[index].size()];
...
I've made a technical decision to pass all my vector-in-vector objects as pointers because I don't want them to be copied and passed to the function. It's because those vectors usually hold more than 1000 strings.
But what I don't understand is why I get the compile error at those two lines about the assignment sign (=)
synonym1=source_words[index][rand()%source_words[index].size()];
synonym2=target_words[index][rand()%target_words[index].size()];
It says this: No operator "=" matches these operands
Upvotes: 0
Views: 45
Reputation: 19607
synonym1 = source_words[index][rand() % source_words[index].size()];
synonym2 = target_words[index][rand() % target_words[index].size()];
would be a valid code if you used references, which you should have.
As for pointers, you'll need this:
synonym1 = (*source_words)[index][rand() % (*source_words)[index].size()];
synonym2 = (*target_words)[index][rand() % (*target_words)[index].size()];
That's called dereferencing (parentheses for proper operator associativity).
Without it, the pointer is canceled out by [index]
(UB if index != 0
), but luckily, it doesn't compile, because you end up with assigning std::vector<std::string>
to std::string
.
Similarly, with source_words[index].size()
, you're getting the size of the std::vector<std::vector<std::string>>
and not std::vector<std::string>
.
Upvotes: 2
Reputation: 3527
Every time there's a chance to use references over pointers, go ahead and do that.
Note that if at some point, you must use a pointer to a vector, you can always use the at
function like
synonym1 = source_words->at(index)[rand() % source_words->at(index).size()];
synonym2 = target_words->at(index)[rand() % target_words->at(index).size()];
I know some people prefer to call like myfunc(&vector)
(to somehow "make it obvious" that the function being called is going to modify the vector), so that's a way to work with pointers to vectors, or dereference the pointer as LogicStuff pointed out and then use the []
operator.
A very important fact though, is that the at
function checks whenever the "index" is valid or not, while the operator []
doesn't.
Upvotes: 1