如何像在javascript中一样"push" c ++映射

How to "push" c++ map like it's done in javascript

本文关键字:一样 push 映射 何像 javascript      更新时间:2023-10-16

在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] = { '' };
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++示例中,我想遍历 while(( 循环,就像我在 for(( 循环 js 示例中所做的那样,我做得很好。 在C++我需要构建一个新数组(就像我的 males[] js 数组一样(并将迭代的数据推送到其中。

如何获得 C++ std::map 以正确执行此操作? 我什至使用std::map还是应该使用其他东西?

试试这个:

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"));

使用哪个容器取决于它的用途。

对于向量,您可以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");