如何计算向量中矩阵的实例



我正在尝试使用以下方法计算矩阵的实例:

// setup some matrices to count instances of
std::vector<std::vector<int>> matrix1({{1, 2, 3},
{4, 5, 6}});
std::vector<std::vector<int>> matrix2({{1, 2, 3},
{4, 5, 6}});
std::vector<std::vector<int>> matrix3({{7, 8, 9},
{10, 11, 12}});
std::vector<std::vector<int>> matrix4({{13, 14, 15},
{16, 17, 18}});
// collect matrices into a vector
std::vector<std::vector<std::vector<int>>> vector_of_matrices({matrix1, matrix2, matrix3, matrix4});
assert(4 == vector_of_matrices.size());
// convert into a set, so that we know how many unique elements there are
std::set<std::vector<std::vector<int>>> s(vector_of_matrices.begin(), vector_of_matrices.end());
assert(3 == s.size());
// store the counts, index wise
std::vector<int> counts_;
counts_.reserve(s.size());
// handle to set iterator
auto setIt = s.begin();
// iterate over number of unique elements in vector_of_matrices
for (int i=0; i < s.size(); i++){
// count instances of current set setIt
counts_[i] = std::count(vector_of_matrices.begin(), vector_of_matrices.end(), *setIt);
// increment set
std::advance(setIt, 1);
}

此代码在调用std::count的线路上分段故障。有人建议让这个代码发挥作用吗?预期输出将是一个包含3个元素的std::vector<int>,一个2和两个1s。

reserve():上的cppreference页面

将向量的容量增加到大于或等于new_cap的值。如果new_cap大于当前容量((,则分配新的存储,否则该方法不执行任何操作。

reserve((不会更改向量的大小

(强调矿(

所以counts_向量的大小实际上是0,这意味着count_[i] = ...是未定义的行为。

不需要调用reserve,只需使用std::vector构造函数来设置初始大小:

std::vector<int> counts_(s.size());

最新更新