首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

stl 容器怎样解决这个有关问题

2014-01-03 
stl 容器怎样解决这个问题。先上部分代码来说明问题。#include stdafx.h#include iostream#include str

stl 容器怎样解决这个问题。
先上部分代码来说明问题。


#include "stdafx.h"

#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;

typedef struct tagItem{
string name;
int value;
}Item;

typedef struct tagSum{
string name;
vector<int> vec;
}Sum;

Item items[] = {
{"he", 1}, 
{"he", 4}, 
{"he", 7},
{"wang", 2}, 
{"wang", 5}, 
{"wang", 8}
};

// 需要生成两个对象。
// Sum sum1 = {"he", [1,4,7]};
// Sum sum2 = { "wang", [ 2,5,8 ]}


int _tmain(int argc, _TCHAR* argv[])
{
Sum sum;

printf("press a key to exit\n");
_getch();
return 0;
}



就好比说,一个人,1号花了1块钱,2号花了4块钱,3号花了7块钱, 
另一个人,1号花了2块钱,2号花了5块钱,3号花了8块钱, 
这些数据,我们已经把它装到items 变量了,
现在想统计一下, 每一个人,每天花了多少钱
其结果应该是 {"he",[1,4,7]}, {"wang, [2,5,8]},
假如有第三人, 或可能是{"li",[4,7,8,9,10]}, 
总之,是一个名称后面对应着一个数组。

这个问题, 如果用纯c 一刀一枪的,又是分配内存,又是copy 名称,太累。
感觉用stl 的map, 稍稍insert 一下,可能就能解决问题。一个键是名称,
一个值是数组。
stl我不熟,哪位肯不吝赐教!

[解决办法]
map<string, vector<float> >

[解决办法]
这个意思?
map<char*, int*> items;
int arr1[] = {1, 4, 7};
int arr2[] = {2, 5, 8};
items.insert(make_pair<char*, int*>("he",arr1)); 
items.insert(make_pair<char*, int*>("wang",arr2)); 

[解决办法]
用map<string, list<int>>这样的结构,map和list的用法可以参考STL手册。

引用:
先上部分代码来说明问题。

#include "stdafx.h"

#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;

typedef struct tagItem{
string name;
int value;
}Item;

typedef struct tagSum{
string name;
vector<int> vec;
}Sum;

Item items[] = {
{"he", 1}, 
{"he", 4}, 
{"he", 7},
{"wang", 2}, 
{"wang", 5}, 
{"wang", 8}
};

// 需要生成两个对象。
// Sum sum1 = {"he", [1,4,7]};
// Sum sum2 = { "wang", [ 2,5,8 ]}


int _tmain(int argc, _TCHAR* argv[])
{
Sum sum;

printf("press a key to exit\n");
_getch();
return 0;
}



就好比说,一个人,1号花了1块钱,2号花了4块钱,3号花了7块钱, 
另一个人,1号花了2块钱,2号花了5块钱,3号花了8块钱, 
这些数据,我们已经把它装到items 变量了,
现在想统计一下, 每一个人,每天花了多少钱
其结果应该是 {"he",[1,4,7]}, {"wang, [2,5,8]},
假如有第三人, 或可能是{"li",[4,7,8,9,10]}, 
总之,是一个名称后面对应着一个数组。

这个问题, 如果用纯c 一刀一枪的,又是分配内存,又是copy 名称,太累。
感觉用stl 的map, 稍稍insert 一下,可能就能解决问题。一个键是名称,
一个值是数组。
stl我不熟,哪位肯不吝赐教!

[解决办法]
map<string, vector<float> > item;
item["he"].push_back(1);
item["he"].push_back(2);
item["he"].push_back(3);
item["wang"].push_back(2);
item["wang"].push_back(5);
item["wang"].push_back(8);

热点排行