jana
jana

Reputation: 81

Get the size of a vector that is an element in a vector that is a pointer

for(int i=0; i < synthesizer_->GetNotation()->size(); i++){
   for(int j=0; j < synthesizer_->GetNotation()[i]->size(); j++){}
}

I want to display the elements of a vector of vectors, row by row. The error (right after [i]) is:

base operand of '->' has non-pointer type 'std::vector<std::vector<std::basic_string<char> > >'

GetNotation() returns a pointer to the vector of vectors.

I'm assuming the error is telling me the syntax is incorrect (but I'm not sure).

I don't know how else to access the contained vectors except by the index in a bracket. I've searched and can't find an explanation or code example.

protected: std::vector<std::vector<std::string> > notation_;
std::vector<std::vector<std::string> >* GetNotation(){return &notation_;}

Upvotes: 0

Views: 179

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 597360

If GetNotation() returns a vector* pointer (why not a vector& reference?), then you need to first dereference the pointer to access the vector being pointed at, before you then try to access the vector's operator[], eg:

for(size_t i = 0; i < synthesizer_->GetNotation()->size(); ++i){
   for(size_t j = 0; j < (*(synthesizer_->GetNotation()))[i].size(); ++j){
      // use (*(synthesizer_->GetNotation()))[i][j] as needed...
   }
}

Which would be much easier to manage and read if you call GetNotation() only one time and cache the result in a local variable, eg:

auto notation = synthesizer_->GetNotation();
for(size_t i = 0; i < notation->size(); ++i){
   auto &strings = (*notation)[i];
   for(size_t j = 0; j < strings.size(); ++j){
     // use strings[j] as needed...
   }
}

Alternatively:

auto &notation = *(synthesizer_->GetNotation());
for(size_t i = 0; i < notation.size(); ++i){
   auto &strings = notation[i];
   for(size_t j = 0; j < strings.size(); ++j){
     // use strings[j] as needed...
   }
}

That being said, you could use iterators instead of indexes:

auto notation = synthesizer_->GetNotation();
for(auto i = notation->begin(); i != notation->end(); ++i){
   auto &strings = *i;
   for(auto j = strings.begin(); j != strings.end(); ++j){
     // use *j as needed...
   }
}

In which case, you could use range-based for loops instead, eg:

for(auto &strings : *(synthesizer_->GetNotation())){
   for(auto &str : strings){
     // use str as needed...
   }
}

Upvotes: 1

Related Questions