c++ - 循环退出 vector 并出现错误进程已完成,退出代码为 -1073741819

标签 c++ loops vector

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/

相关文章:

Visual Studio 2013 中的 C++ - <Class> 未定义

c++ - 与自定义命名空间的链接失败未解析的外部符号

c++ - 从 .dll 覆盖类/函数

PHP如何计算foreach循环中的相同单词

javascript - 我如何循环遍历 Javascript 对象数组,将对象分配为其中其他对象的子对象?树/层次结构

c++ - std::vector 不会为多个 vector 条目创建 cv::Mat 的新引用 - 初始化矩阵时数据会被覆盖

c++ - C++ 中的洗牌 vector

c++ - C、C++、数据类型、运算符和表达式

vba - 使用连续数据列中的特定条件选择范围

c++ - 在类中使用 "class[i]"访问 vector ,例如类将是 vector