C++ 尝试推送向量<;int>;映射到计算模式

C++ 尝试推送向量<;int>;映射到计算模式,c++,vector,map,C++,Vector,Map,我试图在映射中插入一个向量值(v[I]),并将第二个变量作为输入第一个变量的次数的计数器 仔细考虑伪代码,我很确定我需要一个for循环来运行向量并将值插入映射,我可以创建一个int计数器=1;然后将其作为第二个值插入,如果已经存在,则增加它?我尝试了一些方法,但都没有成功,任何输入都是有帮助的 我的代码: std::pair<std::map<int, int>::iterator, bool> temp; temp = mInt.insert(std::pair<

我试图在映射中插入一个向量值(v[I]),并将第二个变量作为输入第一个变量的次数的计数器

仔细考虑伪代码,我很确定我需要一个for循环来运行向量并将值插入映射,我可以创建一个int计数器=1;然后将其作为第二个值插入,如果已经存在,则增加它?我尝试了一些方法,但都没有成功,任何输入都是有帮助的

我的代码:

std::pair<std::map<int, int>::iterator, bool> temp; 
temp = mInt.insert(std::pair<int, int>(v[i], counter)); 
if (temp.second == false) { counter++; } 
if (counter >= mode) { mode = counter; }
std::对温度;
温度=铸币插入(标准::对(v[i],计数器));
如果(temp.second==false){counter++;}
如果(计数器>=mode){mode=counter;}

我的理解是,您希望迭代向量。向量中的每个元素都将成为std::map结构的键(或索引)。相应的值将是一个计数器

最终结果是std::map结构将包含向量中每个项重复多少次的计数

我会这样做:

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

int main (){

  // Set up a vector of items.  Our items are ints, but any object that
  // can be inserted as a map key is fine.
  std::vector<int> v { 1, 2, 4, 8, 16, 32, 64, 128, 4, 8, 16, 8 };

  // Set up a std::map where the "key" (or index) is the same type as
  // the vector's elements.  The "value" will be our counter.
  std::map<int,size_t> m;

  // Iterate over the vector.  Use each element as a map key. Increment
  // the value indexed by the key.  This is our counter.
  for( auto e : v ) {
    m[e]++;
  }


  // Now iterate over the map, printing out the key, and its
  // corresponding count.
  for ( auto e : m ) {
    std::cout << e.first << " => " << e.second << "\n";
  }


  return 0;
}

C++实现可以使用<代码> STD::unOrdEdMultMux/Cuff>。这将更接近Perl版本

无序映射
将计数算法从O(n logn)降低到O(n)摊销时间复杂度。但是,根据您的需要,可能需要对输出进行排序,这也会带来成本。但是,由于预计向量中会有重复的元素,这意味着映射或无序映射的大小(在元素数量上)将小于向量。因此,即使需要排序的输出,无序的地图也可能是一个净胜利。

Hi,@Cellery72。你能显示你的代码还是伪代码?你问的是/否问题,但我相信你要的不仅仅是是是/否。准确地展示你所做的尝试以及你预期的输入和输出将有助于他人帮助你。很抱歉,这是我迄今为止的代码std::pair temp;温度=铸币插入(标准::对(v[i],计数器));if(temp.second==false){counter++;}if(counter>=mode){mode=counter;
my @v = ( 1, 2, 4, 8, 16, 32, 64, 128, 4, 8, 16, 8 );
my %m;
$m{$_}++ for @v;
print "$_ => $m{$_}\n" for sort { $a <=> $b } keys %m;