LE:如果它有任何相关性,我正在使用 CLion。该程序不打印任何内容。
我需要处理一个 vector ,其中包含 name card_type
形式的字符串 vector ,并按字母顺序显示所有卡片以及每张卡片的实例数。输出应该类似于:
a_card 1
mastercard 4
visa 3
我到目前为止的代码,退出时出现错误 Process finished with exit code -1073741819
。什么问题?
#include <iostream>
#include <vector>
#include <string>
void stats(const std::vector<std::vector<std::string>>& vec) {
std::vector<std::pair<std::string, int>> orderedCards;
for (const auto& client : vec){ //scan database for cards and make ordered vector of pairs
if (orderedCards.empty()){ //insert first pair to empty vector
orderedCards.push_back(std::make_pair(client[1],1));
}else{ //for each new client scan vector and add new client/increment counter
for (auto pair = orderedCards.begin(); pair != orderedCards.end(); ++pair){
if (client[1][0] < pair->first[0]){ //compare first letter of new client and existing client
orderedCards.insert(pair, std::make_pair(client[1], 1));// if its smaller, insert in front
break;// break iteration and go for next client
} else if (client[1] == pair->first){ //if theyre the same, increment counter
pair->second+=1;
break;
} else if (pair+1 == orderedCards.end()) //if end is reached, there was no existing client thus add new one with high letter
orderedCards.push_back(std::make_pair(client[1], 1));
}
}
}
for (const auto& count : orderedCards)
std::cout<<count.first<<" "<<count.second<<std::endl; //print on each line card and counter
}
std::vector<std::vector<std::string>> dataBase;
int main()
{
dataBase={{"name", "bankcard"},{"name", "visa"},{"name", "bankcard"},{"name", "mastercard"},{"name", "bankcard"},{"name", "visa"}};
stats(dataBase);
return 0;
}
最佳答案
@xampierre 这里有一个更简单的函数,不使用 std::sort 和算法库
void stats(const std::vector<std::vector<std::string>>& vec)
{
std::map<std::string, int> orderedCards;
for(auto & client : vec)
{
auto it = orderedCards.insert(std::make_pair(client[1],1));
if (!it.second) // this means that the key was already in the map
it.first->second+=1;
}
for (const auto& count : orderedCards)
std::cout<<count.first<<" "<<count.second<<std::endl; //print on each line card and counter
}
关于c++ - 循环退出 vector 并出现错误进程已完成,退出代码为 -1073741819,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62979124/