在C++中,我希望像在JavaScript中一样,将键/值对象“推”到一个数组中。
下面是我在JavaScript中通常会做的事情:
var people = [];
var males = [];
people.push({ name: 'david',age: 45,sex: 'male'});
people.push({ name: 'mary',age: 22,sex: 'female'});
people.push({ name: 'alan',age: 52,sex: 'male'});
people.push({ name: 'fred',age: 19,sex: 'male'});
people.push({ name: 'alice',age: 33,sex: 'female'});
for (var i = 0; i < people.length; i++)
{
if (people[i].sex == 'male')
{
males.push({
name: people[i].name,
age: people[i].age,
sex: people[i].sex
});
}
}
这是我在C++中的尝试:
int foo()
{
std::map<std::string, int> aData;
MySQL my;
char szQueryText[200] = { '\0' };
MYSQL_RES *My_result = nullptr;
snprintf(szQueryText, sizeof(szQueryText), "SELECT * FROM %s.object_affixes WHERE objType = %d ORDER BY rowID ASC;", DB_DATA, 1);
My_result = MySQL__query(szQueryText);
int num = my.Query(szQueryText);
while (num > 0)
{
my.NextRow();
num--;
aData.insert('rangeFrom', atoi(my.GetData("rangeFrom")));
}
MySQL__endquery(My_result);
在我的C++示例中,我希望像在for()循环js示例中一样遍历while()循环,我现在做得很好。在C++中,我需要构建一个新数组(就像我的males[] js数组一样),并将迭代数据推入其中。
如何让C++ std::map正确执行此操作?我是否使用std::map,或者我是否应该使用其他东西?
发布于 2018-08-15 05:56:20
试试这个:
struct Person
{
std::string name;
size_t age;
std::string sex;
};
std::vector<Person> database;
Person p("Fred", 21, "male");
database.push_back(p);
C++语言不是JavaScript,所以您必须使用C++方式。
您可以尝试如下所示:
database.push_back(Person("Alice", 19, "female"));
发布于 2018-08-15 06:27:45
使用哪种container取决于它的用途。
对于向量,您可以使用emplace_back(从C++11开始提供):
struct Person
{
std::string name;
size_t age;
std::string sex;
};
std::vector<Person> database;
//...
database.emplace_back("david", 45, "male");
https://stackoverflow.com/questions/51850200
复制相似问题