如何在C ++中创建循环内的结构成员

时间:2018-03-05 14:34:03

标签: c++ loops data-structures

我正在尝试使用C ++中的数据结构来正确组织从循环中收到的一些数据。

我创建了我的结构和我想要的数据。

#include <iostream>
#include <vector>
using namespace std;
#define NumOfProducts 5

struct Product{
    int weight;
    double price;
};

int data1 [5] = { 16, 2, 80, 40, 12070};
int data2 [5] = { 8, 1, 40, 20, 6035};

我想要的是拥有5个“Product”数据结构的成员,每个“weight”从data1中提取,每个“price”从data2中提取。这只是我想要做的事例,因为我的数据集要大得多,所以我认为我真的需要一个for循环而不能手动分配每个案例。

这是我尝试过的。

int main(void){
    Product products[NumOfProducts];
    for (int i=0; i<NumOfProducts; i++){
        products[i].weight = data1[i];
    }
    cout << products[1].weight << endl;
    cout << products << endl;
    return 0;
}

我不确定我得到的结果。

我有5个成员,1个体重,或者我有1个成员,5个体重(作为向量)?我宁愿有5个成员,1个体重,那么我怎样才能改善我的循环?

非常感谢

编辑:似乎我混淆了成员和实例。这段代码看起来更好。

#include <iostream>
#include <vector>
using namespace std;
#define NumOfProducts 5

struct Product{
    int weight;
    double price;
};

vector <int> data1 = { 16, 2, 80, 40, 12070};
vector <int> data2 = { 8, 1, 40, 20, 6035};

int main(void){
    Product products[NumOfProducts];
    for (int i=0; i<NumOfProducts; i++){
        products[i].weight = data1[i];
        products[i].price = data2[i];
    }
    cout << products[1].weight << endl;
    //cout << products << endl; useless as it's the location where the first element of products resides
    return 0;
}

6 个答案:

答案 0 :(得分:1)

根据您当前的数据,您的反对意见是什么?

struct Product{
    int weight;
    double price;
} products[]{{16, 8}, {2, 1}, {80, 40}, {40, 20}, {12070, 6035}};

?如果您要从文件中读取大量数据,那么就应该构建构造函数Product,并使用std::vector<Product> products;作为存储。

请参阅Read in from file into structure

答案 1 :(得分:1)

这样的事情将解释你如何使用矢量&amp; for循环甚至基于具有对象默认和用户定义构造函数的循环的范围:

#include <vector>
#include <iostream>
#include <conio.h> // for _getch()

const unsigned int NumProducts = 5; // Don't like #define I prefer const instead

struct Product {
    int weight;
    float price; // don't need double too much precison & memory consumption

    Product() : weight( 0 ), price( 0.0f ) {}
    Product( int weightIn, float priceIn ) :
        weight( weightIn ),
        price( priceIn ) 
    {}
};

int main() {
    // moved vectors from global; and refrained from "using namespace std" 
    // (bad practice - I prefer to use "std::" so I know what lib they are coming from.
    std::vector<int> weights{ 16, 2, 80, 40, 12070 };
    std::vector<float> prices { 8.0f, 1.0f, 40.0f, 20.0f, 6035.0f };

    // I prefer to use containers "arrays" can be messy. 
    std::vector<Product> products;
    products.reserve( NumProducts ); // 5 Products

    // If Products Are Not Already Created Use 
    // User Defined Constructor & Push Back Into Vector
    for ( unsigned i = 0; i < NumProducts; i++ ) {
        products.push_back( Product( weights[i], prices[i] ) );
    }    
    std::cout << "Output for products vector using Product( int, float ) constructor.\n";
    // To access them for printing you don't need & after the auto.
    for ( auto p : products ) {
        std::cout << "Weight = " << p.weight << ", Price = " << p.price << "\n";
    }
    std::cout << std::endl;

    // If Default Constructed Products Exist:
    std::vector<Product> products2;
    products2.reserve( NumProducts );
    Product product;
    for ( unsigned i = 0; i < NumProducts; i++ ) {
        products2.push_back( product );
    }

    unsigned i = 0; // counter needed for accessing the elements of the data vectors
    for ( auto& p : products2 ) { // Notice the & after auto; without it all values will still be 0.
        p.weight = weights[i];
        p.price = prices[i];
        i++;
    }    
    std::cout << "Output for products2 vector using Product() constructor adding data after.\n";
    // Again don't need the & after p, although it wouldn't hurt if you did use it in this case.
    for ( auto p : products2 ) {
        std::cout << "Weight = " << p.weight << ", Price = " << p.price << "\n";
    }
    std::cout << std::endl;

    _getch();
    return 0;
}

我将构造函数添加到Product结构中有两个主要原因:

  • 首先:即使使用默认构造函数;成员将被初始化为至少0而不是不确定的值。
  • 第二:用户定义构造允许我通过构造函数创建此对象的实例,以便轻松将其推回容器。

没有构造函数并执行类似的操作:

{
    std::vector<Product> products3;
    products3.reserve( NumProducts );
    unsigned idx = 0;
    for ( auto& p : products3 ) {
        p.weight = weights[idx];
        p.price = prices[idx];
        idx++;
    }

    for ( auto& p : products3 ) {
        std::cout << p.weight << ", " << p.price << "\n";
    }
    std::cout << std::endl;
}

由于您只保留了内存并且从未将任何Product实例添加到容器中,因此不会给您任何结果。

答案 2 :(得分:0)

  

我有5个成员,1个体重,或者我有1个成员,5个体重(作为向量)?

您有一个包含Product类型的5个元素的数组。所有Product个实例都有一个weight成员(以及一个未初始化的price成员)。

  

这只是我想要做的事例,因为我的数据集要大很多

如果数据集大得多,那么您可能无法使用自动数组。请改用std::vector

答案 3 :(得分:0)

您有5个Product个对象,每个对象都有自己独立的weight(和price)成员。

您目前正在为每个对象初始化weight的方式,也可以price执行此操作并重新设置。

请注意,如果您尝试在循环中分配任何成员之前尝试阅读任何成员,则表示weight未定义,height未被初始化。

答案 4 :(得分:0)

  

我想要的是拥有5个&#34;产品&#34;数据结构   每个&#34;重量&#34;从data1和每个&#34;价格&#34;中提取摘自   DATA2。

然后写

int main(void){
    Product products[NumOfProducts];
    for (int i=0; i<NumOfProducts; i++){
        products[i].weight = data1[i];
        products[i].price = data2[i];
    }
    //...
    return 0;
}

因此,使用数组weightprice的元素的相应值初始化数组products的每个元素的数据成员data1data2

答案 5 :(得分:-1)

#include <iostream>
#include <vector>
using namespace std;
#define NumOfProducts 5

struct Product{
    int weight;
    double price;
};

vector <int> data1 = { 16, 2, 80, 40, 12070};
vector <int> data2 = { 8, 1, 40, 20, 6035};

int main()
{
    Product products[NumOfProducts];
    for (int i=0; i<NumOfProducts; i++)
    {
        products[i].weight = data1[i];
        products[i].price = data2[i];
    }

    for (int i=0; i<NumOfProducts; i++)
    {
        cout <<"Object "<<i+1<<endl;
        cout <<"Weight = "<< products[i].weight << endl;
        cout <<"Price  = "<< products[i].price << endl;
        cout <<"\n";
    }
    //cout << products << endl; useless as it's the location where the first element of products resides
    return 0;
}

Output:
=======
Object 1
Weight = 16
Price  = 8

Object 2
Weight = 2
Price  = 1

Object 3
Weight = 80
Price  = 40

Object 4
Weight = 40
Price  = 20

Object 5
Weight = 12070
Price  = 6035

无论你想做什么都是正确的。上面是你想要做的代码我是这么认为的。我只是编译并运行代码。它可能已经解决了你的问题。