我正在实现以下数据集,并希望避免通常涉及的冗长操作符号,例如 .
和 ->
选择器等。
struct myList {
double node1 = 2,
node2 = 4,
node3 = 6.6,
node4 = 8
};
如何对非特定选择的节点进行任意求和。例如对于 jQuery,如果这个结构是 JSON,那么我可以这样做:
$(myList).children().each(function() {
sum += Number($(this).val());
});
// Or more generic, given size..
for (var i = 0; i < NUM_MEM; i++) {
sum += $(myList).nth-child(i).val();
}
最佳答案
根据最实际的情况,使用数组、 vector (或列表)或映射。
数组是不灵活的,在编译时固定大小。 std::vector<double>
灵活且易于使用。例如:
#include <iostream>
#include <numeric> // for std::accumulate, also look at <algorithms>
#include <vector>
struct data {
std::vector<double> nodes;
};
int main() {
data d = {{1, 2, 3}};
double sum = std::accumulate(std::begin(d.nodes), std::end(d.nodes), 0);
std::cout << "Total: " << sum << std::endl;
}
使用 std::map<std::string, double>
(或 std::unordered_map
)如果您更愿意使用名称而不是索引。
#include <iostream>
#include <map>
#include <numeric>
#include <string>
struct data {
std::map<std::string, double> items;
};
typedef std::map<std::string, double>::value_type my_map_element;
int main() {
data d = {{{"item1", 1}, {"item2", 2}, {"item3", 42}}};
double sum = std::accumulate(std::begin(d.items), std::end(d.items), 0,
[](double partial, my_map_element const& elt) {
return partial+elt.second;
});
//[](auto partial, auto const& elt) { // C++14
// return partial+elt.second;
//});
std::cout << "Total: " << sum << std::endl;
}
std::accumulate
,像大多数标准算法一样,采用迭代器。您会发现它在通用 C++ 库中随处可见。这使得算法非常灵活 - 它们不依赖于所使用的实际数据结构。
如果您不能更改数据类,您可以使用简单的包装器使它们可迭代(无论如何一次一种类型),使用 std::reference_wrapper
不会有太多麻烦。它的行为非常像引用,但可以存储在集合(和数组)中。
这是一个如何工作的例子:
#include <functional> // for std::reference_wrapper
#include <iostream>
#include <numeric> // for std::accumulate
#include <vector>
struct data
{
double node1, node2, node3;
};
int main()
{
typedef std::vector<std::reference_wrapper<double>> double_wrapper;
data d { 1, 2, 3 };
double_wrapper helper = { d.node1, d.node2, d.node3 };
// You update via the helper or directly
d.node1 = 4;
helper[1].get() = 5; // will update d.node2
// Handy iteration
for (auto& node: helper)
node.get()++;
// And use standard algorithms
std::cout
<< "Sum: "
<< std::accumulate(std::begin(helper), std::end(helper), 0)
<< std::endl;
}
警告:助手/包装器的生命周期与数据对象本身的生命周期密切相关。不要让包装器比数据对象长寿。如果您将外部数据和上面的 vector 之类的东西“重新打包”到一个结构中供您内部使用,出于同样的原因,也要非常小心复制(和移动)语义。
关于jquery - 任意对象成员选择 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23442114/