使用std::vector的互补向量

Complementary vector using std::vector

本文关键字:向量 vector std 使用      更新时间:2023-10-16

我正在C++中编写一个现有的Matlab库。在Matlab中有一个波浪号运算符,~vec是具有1的二进制矢量,其中vec为零,其他地方为0。

更准确地说,我在Matlab 中有这些代码行

        allDepthIdx = [1:nVec]'; 
        goodIdx = allDepthIdx(~offVec);
        goodValues = vec(~offVec);

我正在寻找一种有效的方法来找到索引goodIdx = allDepthIdx(~offVec);。有一种方法,使用std::vector,可以找到在1..nVec中而不在offVec中的索引列表吗?

我提出了这个解决方案,请随时发表评论或提出您的解决方案!

        // First, I sort offVec
        std::sort(offVec.begin(), offVec.end());
        int k(0), idx(-1);
        std::vector<real32_T> goodDepthIdx;
        std::vector<real32_T> goodVal;
        // For j in 1..nVec, I check if j is in offVec
        for (int j = 0; j < nVec; j++)
        {
            k = 0;
            idx = offVec.at(k);
            // I go through offVec as long as element is strictly less than j
            while (idx < j)
            {
                idx = offVec.at(k++);
            }
            if (idx != j) // idx not in offElemsVec
            {
                goodDepthIdx.push_back(j); // Build vector with indices 
                                           // in 1..nVec not in offVec
                goodVal.push_back(vec.at(j)); // Build vector with values
                                           // at these indices
            }
        }
相关文章: