【发布时间】:2022-01-15 01:21:33
【问题描述】:
我有多个存储在映射中的整数二维数组(所有相同维度),每个数组都包含一个分配给数组的唯一字符。例如,我有std::map<std::array<std::array<int>> , char>。
我正在尝试查找具有特定二维坐标的最大整数的数组,并从地图中返回相关字符。我对此的想法是返回地图中在坐标 [r][c] 处具有最大 int 的元素,然后访问 char 的 element.second。我这样做的尝试无济于事。我可以使用循环来做到这一点,但它很慢,如果可能的话我想避免。
我查看了以下链接,但它们与我的问题有很大不同,我无法让它们工作:
How to get min or max element in a vector of objects in c++, based on some field of the object?
感谢您的所有帮助!
我尝试过的:
二维数组和字符的映射:
int main(void)
{
std::array<std::array<int, 3>, 3> arr1 =
{
{
{4, 7, 3},
{2, 6, 0},
{6, 4, 7}
}
};
std::array<std::array<int, 3>, 3> arr2 =
{
{
{5, 8, 2},
{8, 3, 1},
{5, 3, 9}
}
};
std::map<std::array<std::array<int, 3>, 3>, char> myMap;
myMap.insert({ arr1, 'A' });
myMap.insert({ arr2, 'B' });
// Somehow access char that is associated with the array that has max int at location[r][c]
// Anything I've tried with std::max_element does not work here
return 0;
}
包含二维数组和字符的对象数组:
class testClass
{
private:
std::vector<std::vector<int>> myVector;
public:
int score;
char mainChar;
testClass(std::vector<std::vector<int>> inpVector, int inpScore, char inpChar)
{
this->myVector = inpVector;
score = inpScore;
mainChar = inpChar;
}
int returnItem(int row, int col)
{
return myVector[row][col];
}
};
// A pred function to adjust according to your score
bool comparator(const testClass& s1, const testClass& s2)
{
return s1.score < s2.score;
}
int main(void)
{
std::vector<testClass> testVector;
testClass vectorOne
(
{
{ 1,2,3 },
{ 4,5,6 }
}
, 1, 'a');
testClass vectorTwo
(
{
{ 1,2,3 },
{ 4,5,6 }
}
, 2, 'b');
testVector.push_back(vectorOne);
testVector.push_back(vectorTwo);
std::cout << testVector[0].returnItem(0,0);
auto element = std::max_element(testVector.begin(),
testVector.end(), comparator);// I don't know how to get element [r][c] here
return 0;
}
【问题讨论】:
-
只是想了解为什么我被降级。我花了整整 15 分钟试图想出一个中肯而简短的标题,然后准确地说出我想要做什么,提供了 2 篇文章表明我在询问之前做了我的研究,然后提供了 2 个代码示例表明我在询问之前尝试了不同的方法。那么……为什么?
标签: c++ dictionary object c++11 vector