如何使用矢量或地图查找特定键并添加值?

时间:2015-10-07 14:20:49

标签: c++ vector stl

我有一个程序,我想创建一个 STL ,它可以保存每个account_num及其spend的详细信息。换句话说,两个值同时存在。

所以,获取细节。我有一个get_details 功能,其工作是逐个从文件 (存储值)中读取详细信息并获取account_num及其对应spend的值并将其保存到我们制作的 STL 中。

并且,如果account_num已存在,则将其 spend值添加到其< strong>上一个 spend值。

示例:

假设,该文件包含数据作为程序的输入:

account_num         spend
1001                 100  
1001                 200  
1002                 200  
1001                 400  
1002                 100   
1001                 300     
1002                 500

而且,我想要矢量地图形式的输出,其值如下所示:

1001                 1000  
1002                 800  

任何人都可以建议我如何继续这个

3 个答案:

答案 0 :(得分:0)

不知道我对你的问题的理解是否正常。可能你可以创建一个结构(或类,在C ++中这是相同的东西,除了C ++默认具有私有成员),如

struct element 
{
    element(unsigned long account, unsigned long spent)
        : m_account(account)
        , m_spent(spent)
    { }

    // copy constructor should be declared too !

private:
    unsigned long m_account;
    unsigned long m_spent;
}
typedef std::list<element> ListOfElement;

用法:

ListOfElement elementList;
elementList.push_back(element(1001, 100));
elementList.push_back(element(1001, 200));
...

接下来,浏览此列表并填充矢量。 希望这有帮助。

答案 1 :(得分:0)

  

我假设您熟悉地图容器。

现在,看看代码:

void get_details(); 
void display();
map <int , int> M; /* Global map is declared with 'account_num' as key 
                      and 'spend' as its value */   
int main() {
    // do something 
    get_details();   /* call the function */
    display();       /* display the final map */
    // do something
    return 0;
}

void get_details() {
    /* first, start reading from the file which stores the data  */ 
    int account_num;
    int spend;

    while(/* keep on reading the file until EOF is reached */) {

        /*  I'm considering that you are able to read from your file 
            properly and on each iteration we get new values of account_num
            and its spend */

        /*  Now, Look for the account_num value into the map and do the
            following operation */

            M[account_num] += spend;   /* Add the new value if the previous
                                          value already exist or create new
                                          entry with new pair of account_num
                                          and spend */
    }
}

void display() {
    map <int, int> :: iterator it = M.begin();

    for(; it != M.end(); it++) {
        cout << it->first << " " << it->second << endl;
    }
}

仍然难以理解。评论最受欢迎。

答案 2 :(得分:0)

对于此任务,mapunordered_map是合理的选择。适用的代码看起来像这样:

std::ifstream infile("input.txt");
std::map<int, int> values;
int a, b;

std::string ignore;
std::getline(infile, ignore); // read and ignore the initial `account_num spend` line
while (infile >> a >> b)
    values[a] += b;
for (auto const &v : values)
    std::cout << v.first << "\t" << v.second << "\n";

样本数据的结果:

1001    1000
1002    800