[英]manipulations with elements of vector and structure C++
為了了解使用向量的更困難的過程和操作,我決定舉一個非常簡單的例子。 所以,我有向量,它具有結構類型。 結構依次具有3個數組: a
, b
, c
。 我填充它們,然后嘗試在結構中打印第一個數組的元素。 但是我做錯了事,不知道到底是什么,也許是什么。 這是代碼:
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.