c++ - 我可以将列表放入结构中吗?

标签 c++ visual-studio-2010 struct

由于我们的产品有多种颜色,我正在尝试将列表用作结构的一部分。这是我可以做的事情还是我应该只使用数组?无论哪种方式,我都没有在网上找到任何示例。

#include "stdafx.h"
#include<iostream>  
#include<string>  
#include<sstream>  
#include<cctype> 
#include<list>

using namespace std;

////////////////////////////////////////////////////////////////////////////////////////
//  Constances
////////////////////////////////////////////////////////////////////////////////////////

#define N_PRODUCT 3

struct Brand_t {
int Model_Num;
string Product_Name;
list<string> Colors;
} brands [N_COLOR];

////////////////////////////////////////////////////////////////////////////////////////
//  Functions
////////////////////////////////////////////////////////////////////////////////////////


int main()
{
string mystr;
int n;

for (n=0; n < N_PRODUCT; n++)
{
    cout << "Enter Model Number: ";
    std::getline (cin,mystr);
    stringstream(mystr) >> brands[n].model_Num,4;
    cout << "Enter Product Name: ";
    getline(cin,classrooms[n].Product_Name);
    list<string>::iterator it;
    Students.push_back ("Red");
    Students.push_back ("Yellow");
    Students.push_back ("Blue");
}

return 0;
}

最佳答案

是的,这是可以做到的。多亏了 RAII,list 对象将根据结构的生命周期自动初始化和释放。请注意,即使在其他编程语言(如 Object Pascal)中情况并非如此,structclass 在 C++ 中实际上是相同的,唯一的区别是默认值正如其他答案所指出的那样,成员方法和变量的可见性。

你不能放非PODS对象变成 union 体。

我建议您使用 std::vectorstd::array 而不是 C 风格的数组。如果您的数组应该具有动态大小,则 std::vector 可能最有用。如果您使用普通 new 甚至 malloc(),那么您的对象将不会自动释放(甚至不会使用 malloc() 初始化)

关于c++ - 我可以将列表放入结构中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11319383/

相关文章:

c++ - 您最喜欢 C/C++ 性能分析器/分析器的哪些功能?

C++析构函数内存泄漏

c++ - C++类定义中的第三个词

c++ - 如何从 C++ 中的文件夹中读取文件?

c++ - C++11 中 lambda 的非确定性损坏

c - 指向结构体指针的指针

c++ - 首先调用哪个构造函数

visual-studio-2010 - 调试 For 循环;快进

c malloc 导致崩溃

c - 取消引用指向不完整类型的指针 'struct ____'