【问题标题】:How to Get Value of an element in a map Using Row and Column in C++?如何使用 C++ 中的行和列获取地图中元素的值?
【发布时间】: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::findoperator[] 作为地图,或者如果您可以使用C++11 map::at 从地图中获取值。您的地图是用对键控的,所以只需使用用户输入,用它们制作一对并使用map::find,你应该很高兴。

标签: c++ map iterator


【解决方案1】:
Map::const_iterator item_pos = MyMap.find(make_pair(userInputRow, userInputCol));
if(item_pos != MyMap.end())
    cout << item_pos->second << endl;

编辑: 请修复这 2 行:

row.push_back(row_array[i]);
column.push_back(col_array[i]);

【讨论】:

  • 因为你在这2行中有一个错误:row.push_back(row_array[i]); column.push_back(col_array[i]);
  • 那我该怎么办?用什么替换它们?
  • 好的。我得到了它。我使用了插入功能。一切都是好的。谢谢。
【解决方案2】:

您的映射不是保存两个向量,而是从一对字符串映射到另一个字符串。 我想知道您使用这种结构而不是向量的用例是什么?

您已经可以访问代码中的地图元素:

cout << MyMap[make_pair(row[i], column[j])];

请注意,如果条目不存在,[] 运算符将插入到映射中,但并非总是如此。

您可以像每个容器一样在地图上进行迭代,并按其键排序:

for(const auto &p : MyMap) {
    std::cout << p.second << std::endl; 
}

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 1970-01-01
    • 2021-05-26
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    相关资源
    最近更新 更多