我有多個存盤在地圖中的整數二維陣列(所有相同維度),每個陣列都包含一個分配給陣列的唯一字符。例如,我有std::map<std::array<std::array<int>> , char>.
我試圖找到具有特定 2d 坐標的最大整數的陣列,并從地圖中回傳關聯的字符。我對此的想法是回傳地圖中在坐標 [r][c] 處具有最大 int 的元素,然后訪問 char 的 element.second。我這樣做的嘗試無濟于事。我可以使用回圈來做到這一點,但它很慢,如果可能的話我想避免。
我已經查看了以下鏈接,但它們與我的問題有很大不同,我無法讓它們作業:
如何根據物件的某些欄位在 C 中的物件向量中獲取最小或最大元素?
如何根據結構中的某些欄位在 C 中的結構向量中獲取最小或最大元素
感謝您的所有幫助!
我試過的:
二維陣列和字符的映射:
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;
}
uj5u.com熱心網友回復:
如果不查看地圖中的每個 2D 陣列,就不可能做到這一點,因為您需要比較所有這些陣列,以便找出在給定坐標處哪個具有最大整數。(使用回圈是不可避免的)
考慮一個myMap具有您描述的屬性的地圖,即它具有型別std::map<std::array<std::array<int>> , char>并且已經填充。然后這段代碼會做你想做的事:
int max = minimum_int_value;
char myChar = '\0';
for (auto const& entry : myMap) {
if (entry.first[r][c] > max) {
max = entry.first[r][c];
myChar = entry.second;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/414756.html
標籤:
