【问题标题】:Get the size of a vector that is an element in a vector that is a pointer获取作为指针向量中元素的向量的大小
【发布时间】:2020-12-29 19:22:03
【问题描述】:
for(int i=0; i < synthesizer_->GetNotation()->size(); i++){
   for(int j=0; j < synthesizer_->GetNotation()[i]->size(); j++){}
}

我想逐行显示向量的元素。 错误(在[i] 之后)是:

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

GetNotation() 返回一个指向向量向量的指针。

我假设错误告诉我语法不正确(但我不确定)。

除了通过括号中的索引之外,我不知道如何访问包含的向量。我已经搜索过,但找不到解释或代码示例。

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

【问题讨论】:

  • GetNotation() 返回什么?
  • 显示GetNotation的返回类型。不要试图用语言来描述它,只显示函数的确切声明。
  • GetNotation() 返回一个指向向量向量的指针。

标签: c++ for-loop pointers vector size


【解决方案1】:

如果GetNotation() 返回一个vector* 指针(为什么不是vector&amp; 引用?),那么您需要先取消引用指针以访问被指向的vector,然后再尝试访问向量的operator[],如:

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...
   }
}

如果你只调用一次GetNotation() 并将结果缓存在一个局部变量中,这将更容易管理和阅读,例如:

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...
   }
}

或者:

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...
   }
}

话虽如此,您可以使用迭代器而不是索引:

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...
   }
}

在这种情况下,您可以改用range-based for loops,例如:

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

【讨论】:

  • 非常感谢。
猜你喜欢
  • 1970-01-01
  • 2011-03-12
  • 2020-04-12
  • 1970-01-01
  • 2020-09-08
  • 2018-12-16
  • 1970-01-01
  • 2015-12-06
  • 1970-01-01
相关资源
最近更新 更多