gpt4 book ai didi

c++ - 如何使用vector和struct?

转载 作者:太空狗 更新时间:2023-10-29 20:05:12 51 4
gpt4 key购买 nike

我需要对字符串中的字母进行计数,按计数和 cout 结果对它们进行排序。为此,我尝试使用 vectorstruct。这是我的部分代码,但它不起作用,因为我不知道如何实现某些东西:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

struct int_pair{
int key;
int value;
};

bool sort_by_value(int_pair left, int_pair right){
return left.value < right.value;
}

int main() {
string characters = "aasa asdfs dfh f ukjyhkh k wse f sdf sdfsdf";
vector<int_pair> most_frequent;

for (string::size_type i = 0; i <= characters.length(); i++) {
int int_char = (int)characters[i];
most_frequent[int_char]++; <-- I want to do something like this, but it's not working
}

sort(most_frequent.begin(), most_frequent.end(), sort_by_value);

for (vector<int_pair>::iterator it = most_frequent.begin(); it != most_frequent.end(); ++it) <-- is this call correct?
cout << " " << it->key << ":" << it->value << endl;

return 0;
}

在这段代码中,我有 2 个部分不知道如何处理:

most_frequent[int_char]++; <-- I want to do something like this, but it's not working 

for (vector<int_pair>::iterator it = most_frequent.begin(); it != most_frequent.end(); ++it) <-- is this call correct?

也许您可以在此代码中看到任何其他错误和潜在问题。

最佳答案

我会使用 std::map 来确定每个字母的频率,然后将其复制到多重映射中,同时反转键和值以使它们按顺序排列。

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

template<class T, class U>
std::pair<U,T> flip_pair(const std::pair<T,U>& p) {
return std::make_pair(p.second,p.first);
}

int main(){
std::string characters = "zxcvopqiuweriuzxchajksdui";
std::map<char,int> freq;
std::multimap<int,char> rev_freq;

// Calculate the frequency of each letter.
for(char c: characters){
freq[c]++;
}

// Copy the results into a multimap with the key and value flipped
std::transform(std::begin(freq), std::end(freq),
std::inserter(rev_freq, rev_freq.begin()),
flip_pair<char,int>);

// Print out the results in order.
for(std::pair<int,char> p : rev_freq){
std::cout << p.first << ": " << p.second << std::endl;
}
};

关于c++ - 如何使用vector和struct?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14840082/

51 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com