我是C++的新手,对如何处理这个问题感到非常困惑。在Javascript中,我可以像这样很容易地动态访问一个对象:
function someItem(prop) {
const item = {
prop1: 'hey',
prop2: 'hello'
};
return item[prop];
}在C++中,我假设我必须使用结构体,但在此之后,我被困在如何动态访问结构体成员变量的问题上。
void SomeItem(Property Prop)
{
struct Item
{
Proper Prop1;
Proper Prop2;
};
// Item[Prop] ??
}这可能是很糟糕的代码,但我对如何处理它感到非常困惑。
发布于 2021-09-22 17:21:24
这是一个简单的示例,说明如何创建struct的实例,然后访问其成员:
#include <iostream>
#include <string>
struct Item {
std::string prop1 = "hey";
std::string prop2 = "hello";
};
int main() {
Item myItem;
std::cout << myItem.prop1 << std::endl; // This prints "hey"
std::cout << myItem.prop2 << std::endl; // This prints "hello"
return 0;
}正如评论中提到的,看起来你可能需要一张地图。映射具有与之关联的键和值,例如,您可以将键"prop1"与值"hey"相关联
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, std::string> myMap;
myMap["prop1"] = "hey";
myMap["prop2"] = "hello";
std::cout << myMap["prop1"] << std::endl; // This print "hey"
std::cout << myMap["prop2"] << std::endl; // This print "hello"
return 0;
}第一种被认为是C++中“正常”的struct用法,而另一种则更适用于必须通过键查找的情况
发布于 2021-09-22 16:45:27
正如评论中提到的,在C++中,您不会为此定义自定义结构,而是使用std::unordered_map。我不知道Javascript,但是如果Property是一个枚举(它可能是经过小修改的其他东西),并且return item[prop];应该返回一个字符串,那么这可能很接近:
#include <string>
#include <unordered_map>
#include <iostream>
enum class Property { prop1,prop2};
std::string someItem(Property p){
const std::unordered_map<Property,std::string> item{
{Property::prop1,"hey"},
{Property::prop2,"hello"}
};
auto it = item.find(p);
if (it == item.end()) throw "unknown prop";
return it->second;
}
int main(){
std::cout << someItem(Property::prop1);
}std::unordered_map确实有一个operator[],您可以像使用return item[p];一样使用它,但是当没有找到给定键的元素时,它会将一个元素插入到映射中。这并不总是可取的,并且当贴图为const时也不可能。
https://stackoverflow.com/questions/69287923
复制相似问题