简体   繁体   English

存储和访问字符串集合(STD C ++)

[英]Storing and accessing a collection of strings (STD C++)

SKU1       SKU2        Description
"01234"    "34545"     "White Bread"
"01545"    "34236"     "Wheat Bread"

I need to cross-reference these three fields, ie retrieve SKU2 while knowing SKU1, SKU1 while knowing SKU2, and Description while knowing either SKU1 or SKU2. 我需要交叉引用这三个字段,即在知道SKU1时获取SKU2,同时知道SKU2时获取SKU1,并且在知道SKU1或SKU2时获取描述。

I'm curious - what is the best way to do this? 我很好奇-最好的方法是什么? Vectors using search() or find()? 使用search()或find()的向量? Using a map somehow? 以某种方式使用地图?

I currently have it working using a vector< vector<string> > , looping through the 'parent' vectors and the 'child' vectors, comparing the values, but this seems primitive. 我目前使用vector< vector<string> > ,循环遍历'父'向量和'子'向量,比较值,但这似乎是原始的。

Basically, I need a vector that uses any of its strings as an index to return one of the two other values. 基本上,我需要一个使用任何字符串作为索引的向量来返回其他两个值中的一个。 Is the general way I'm doing it considered acceptable/optimal? 我这样做的一般方式是否被认为是可接受/最佳的?

vector< vector<string> > products;

int i = 0;
for( i = 0; i < 2; ++i)
{
    products.push_back( vector<string>() );

    products[i].push_back( "SKU1" );
    products[i].push_back( "SKU2" );
    products[i].push_back( "Description" );

}

Thanks for your assistance. 谢谢你的协助。

I would recommend using two maps that index into an object that has the information you need: 我建议使用两个映射到具有所需信息的对象的索引:

struct MyInfo
{
  std::string SKU1;
  std::string SKU2;
  std::string Description;
};

std::map<std::string, MyInfo *> SKU1map;
std::map<std::string, MyInfo *> SKU2map;

MyInfo * newProduct = new MyInfo; ///Do not forget to delete!!
newProduct->SKU1 = //SKU1 value
newProduct->SKU2 = //SKU2 value
newProduct->Description = //Description value

SKU1map[newProduct->SKU1] = newProduct;
SKU2map[newProduct->SKU2] = newProduct;

This will be a decently fast implementation(much better than linear search), and if you deal with many product instances, then it will also be more memory efficient. 这将是一个相当快的实现(比线性搜索好得多),如果你处理许多产品实例,那么它也将更有效的内存。

Build three std::map<std::string, std::string> s: one to map SKU1s to SKU2s, one to map SKU1s to Descriptions, and one to map SKU2s to Descriptions. 构建三个std::map<std::string, std::string> s:一个将SKU1映射到SKU2,一个将SKU1映射到Description,将一个SKU2映射到Description。 (Better yet, use std::unordered_map, if you have it (C++0x)). (更好的是,使用std :: unordered_map,如果你有它(C ++ 0x))。

This is assuming that you have a lot of data and are prioritizing speed rather than memory usage. 这假设您拥有大量数据并且优先考虑速度而不是内存使用情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM