我有一个随机对象如下
struct myObject
{
int numberOfSymbols;
std::vector<int> symbolNumbers;
std::vector<int> Pins;
std::vector<std::string> pinNumList;
std::map<std::string, std::string> pinNumNameMap;
}
std::vector<myObject> m_myObject;
一个函数用信息加载这个myObject向量。我需要对填充的数据进行一些完整性检查,如下所示:
查看所有对象具有相同数量的Pins
和pinNumNameMap
,然后根据该比较结果执行操作。
我不确定如何分组/找到具有相同针数的对象,因为有时这个向量可以长到50-100个对象。我是来自C#的C ++新手。在C#中我们使用lambda expressoins / iterators等来做这个...不确定我们如何在C ++中做到这一点
答案 0 :(得分:1)
您需要定义一个自定义operator==
来循环Pins
和pinNumNameMap(顺便说一下,我刚刚回答了另一个关于在向量here中比较自定义对象的问题。)
以下是我提出的内容,但可能不完全符合您的要求,具体取决于您是否需要Pins
和pinNumNameMap
中的所有条目完全匹配,或者是否需要比较容器就够了。
编辑:我将这两个部分合并为一个,以说明可能的用途。
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <list>
#include <functional>
struct myObject
{
int numberOfSymbols;
std::list<int> symbolNumbers;
std::list<int> Pins;
std::list<std::string> pinNumList;
std::map<std::string, std::string> pinNumNameMap;
friend bool operator == (const myObject& _this, const myObject& _other)
{
// Check if entry sizes match
if (_this.Pins.size() != _other.Pins.size() ||
_this.pinNumNameMap.size() != _this.pinNumNameMap.size())
{
return false;
}
// Now check if the things inside the entries also match
bool same(true);
for (auto this_it = _this.Pins.begin(), other_it = _other.Pins.begin(); this_it != _this.Pins.end(); ++this_it, ++other_it)
{
same &= (*this_it == *other_it);
}
for (const auto& name : _this.pinNumNameMap)
{
same &= (_other.pinNumNameMap.find(name.first) != _other.pinNumNameMap.end() &&
_other.pinNumNameMap.at(name.first) == name.second);
}
return same;
}
};
// std::reference_wrapper is used when you want to
// store references to objects in a container like
// std::vector (you can't store myObject&)
typedef std::reference_wrapper<myObject> ObjRef;
int main()
{
std::vector<myObject> m_myObject;
// This is your comparison object.
// Use this to identify objectsin the original
// container with matching Pins and pinNumNameMaps.
myObject tmp;
tmp.Pins = {1, 2, 3};
tmp.pinNumNameMap =
{
{"pin 1", "name 1"},
{"pin 2", "name 2"},
{"pin 3", "name 3"}
};
std::vector<ObjRef> objectsWithCertainPins;
for (auto& obj : m_myObject)
{
if (obj == tmp)
{
// Use std::reference_wrapper to avoid
// copying large myObject instances
objectsWithCertainPins.emplace_back(std::ref(obj));
}
}
// Now you can iterate over objects in your
// objectsWithCertainPins container.
for (auto& obj : objectsWithCertainPins)
{
std::cout << "Pins:";
for (const auto& p : obj.get().Pins)
{
std::cout << " " << p;
}
std::cout << "\n";
}
return 0;
}