繁体   English   中英

向量和结构C ++元素的操作

[英]manipulations with elements of vector and structure C++

为了了解使用向量的更困难的过程和操作,我决定举一个非常简单的例子。 所以,我有向量,它具有结构类型。 结构依次具有3个数组: abc 我填充它们,然后尝试在结构中打印第一个数组的元素。 但是我做错了事,不知道到底是什么,也许是什么。 这是代码:

using namespace std;

struct hl {
    int a [3];
    int b [3];
    int c [3];
};

int main()
{
  vector<hl> vec;
  struct hl he;

  for (int i = 0; i!=3; ++i) {
      int aa = 12;
      int bb = 13;
      int cc = 14;

      he.a[i]= aa+i;
      cout <<"Hello.a["<< i << "]=  "<<he.a[i]<<endl;
      he.b[i]= bb+i;
      he.c[i]= cc+i;
  }

  for (std::vector<hl>::iterator it = vec.begin() ; it != vec.end(); ++it) {
    //print arr.a[n]
  }

  return 0;
}

在填充结构数组的循环之后,添加以下语句

vec.push_back( he );

然后您可以输出向量中包含的结构的第一个数组的元素

for ( int x : vec[0].a ) std::cout << x << ' ';
std::cout << std::endl;

或者你可以写

for ( const hl &he : vec )
{
   for ( int x : he.a ) std::cout << x << ' ';
   std::cout << std::endl;
}  

或者您可以显式使用vector的迭代器

for ( std::vector<h1>::iterator it = vec.begin(); it != vec.end(); ++it )
{
   for ( size_t i = 0; i < sizeof( it->a ) / sizeof( *it->a ); i++ )
   {
      std::cout << it->a[i] << ' ';
   }
   std::cout << std::endl;
}

代替声明

for ( std::vector<h1>::iterator it = vec.begin(); it != vec.end(); ++it )

你也可以写

for ( auto it = vec.begin(); it != vec.end(); ++it )

您没有将元素he添加到向量中。 你需要做

vec.push_back(he);

迭代应如下所示:

for(std::vector<hl>::iterator it = vec.begin(); it != vec.end(); ++it) {
    std::cout << it->a[0] << ", " << it->a[1] << ", " << it->a[2] << std::endl;
}

同样,在C ++中,您不需要在struct / class变量声明前加上struct关键字。 这是C风格。 您只需要:

hl he;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM