如何计算C++中向量的重复条目

J. *_*Doi 1 c++ armadillo

我正在使用Armadillo在C++中进行线性代数计算.

例如,有一个

vector a = (1,1,2,2,0,2,1,0)
Run Code Online (Sandbox Code Playgroud)

我希望返回一个矩阵

(0, 2) //means 0 shows 2 times in the vector
(1, 3) //1 shows 3 times
(2, 3) //2 shows 3 times
Run Code Online (Sandbox Code Playgroud)

有什么功能可以完成这样的工作吗?

pad*_*ddy 6

如评论中所述,您可以使用a std::map来收集结果.然后您可以根据需要转换为矩阵.您可以跳过映射步骤并直接使用矩阵,如果它已经预先初始化了您所追踪的行.

至于执行此操作的函数,您可以使用std::for_eachfrom <algorithm>和lambda表达式,虽然在循环没问题时它似乎有点过分.

#include <algorithm>
#include <iostream>
#include <vector>
#include <map>

using namespace std;

int main()
{
    vector<int> v{1,1,2,2,0,2,1,0};
    map<int,int> dup;

    for_each( v.begin(), v.end(), [&dup]( int val ){ dup[val]++; } );

    for( auto p : dup ) {
        cout << p.first << ' ' << p.second << endl;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • `for_each`的替代方法是`for(auto x:v)++ dup [x];` (2认同)