C++,如何将 string、int 和 float 值存储到数组中并检索存储的值

Hen*_*wee 3 c++ arrays types

数组可以同时存储int,string和吗?float我看到过一些数组语法,但全部以int array[]or开头string array[], is there a way which a array can store all kind of primitive and string values?

我对 C++ 不太熟悉,但在 java 中,有一个迭代器可以帮助您将这些存储的值转出并允许您显示其中存储的内容。C++也有这个功能吗?

Rud*_*uer 5

对于基本类型,这很容易:它们可以混合成一个unionhttp://www.cplusplus.com/doc/tutorial/other_data_types/ (->Unions).

对于复杂类型,例如string, it gets a little more difficult.

您可能想查看boost::varianthttp://www.boost.org/doc/libs/1_36_0/doc/html/variant.htmlboost::any http://www.boost.org/doc/libs/1_51_0/doc/html /any.html


Jak*_*ers 5

如果这些值相关,则创建一个结构并存储它而不是单个值。前任:

struct person {
    string name;
    int age;
};
person pArray[];
Run Code Online (Sandbox Code Playgroud)