【发布时间】:2014-06-11 18:54:55
【问题描述】:
我想知道如何从地图中获取特定值 它包含两个向量,使用行和列字符串。 例如,如果用户输入“R1”和“C1”,则打印字符串“1”。 在这段代码中,我使用数组下标来访问向量。 如果您能解释如何使用迭代器访问它会很有帮助。
对不起,如果这是重复的问题。
谢谢。
#include <string>
#include <iostream>
#include <vector>
#include <map>
using namespace std;
typedef pair<string, string> Pair;
typedef map<Pair, string> Map;
typedef vector<string> strVec;
int main()
{
const int COL_SIZE = 3;
const int ROW_SIZE = 3;
string row_array[ROW_SIZE] = {"R1","R2","R3" };
string col_array[COL_SIZE] = { "C1", "C2", "C3" };
strVec column;
strVec row;
for (size_t i = 0; i < COL_SIZE; ++i)
{
row.push_back(col_array[i]);
column.push_back(row_array[i]);
}
Map MyMap;
Map::iterator iterator;
string numbers[] = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };
int numberIndex = 0;
for (int i = 0; i < ROW_SIZE; ++i)
{
for (int j = 0; j < COL_SIZE; ++j)
{
MyMap[make_pair(row[i], column[j])] = numbers[numberIndex];
cout << MyMap[make_pair(row[i], column[j])];
++numberIndex;
}
cout << endl;
}
string userInputRow;
cout << "Enter a row: " << endl;
cin >> userInputRow;
string userInputCol;
cout << "Enter a column: " << endl;
cin >> userInputCol;
}
【问题讨论】:
-
考虑使用
map::find或operator[]作为地图,或者如果您可以使用C++11map::at从地图中获取值。您的地图是用对键控的,所以只需使用用户输入,用它们制作一对并使用map::find,你应该很高兴。