使用向量和结构C ++的元素进行操作

时间:2014-08-09 10:59:03

标签: 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;
}

2 个答案:

答案 0 :(得分:2)

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

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

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

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 )

答案 1 :(得分:1)

您没有将元素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关键字前添加struct / class变量声明。这是C风格。 你只需要:

hl he;