我有 4 個整數二維陣列的形式:
{{1,2,3},{1,2,3},{1,2,3}}
前 3(A,B,C) 的大小/形狀為 [1000][3] 和第 4(D) [57100][3]。
A,B,C 中的 3 元素子陣列中的整陣列合都是唯一的,而 D 中的 3 元素子陣列中的整陣列合不是唯一的。
我要做的是在 A、B 或 C 的哪個陣列中找到 D 的子陣列,然后根據我在哪個陣列中找到它來處理它。
我嘗試使用帶有 if 陳述句的嵌套 for 回圈,并一次檢查每個陣列(A->B->C),并在找到它時中斷,但這需要很長時間。
謝謝
uj5u.com熱心網友回復:
正如我的評論所建議的那樣,讓我們??假設您的方法是幼稚的,在for回圈中一次查看一個專案以查看是否找到匹配項。
而不是這樣做,另一種方法是將陣列存盤為 astd::set<std::tuple<int, int, int>>并對集合進行查找。這樣做可以將時間復雜度從線性降低到對數。例如,一個包含 1000 個專案的集合最多有 10 個測驗來最終確定該專案是否存在,而不是必須遍歷所有 1000 個專案。
這是一個未經測驗的示例。請注意,陣列中的資料尚未填充(假設資料已填充到陣列中):
#include <tuple>
#include <set>
#include <array>
#include <iostream>
using TupleSet = std::set<std::tuple<int, int, int>>;
int A[1000][3];
int B[1000][3];
int C[1000][3];
int D[57100][3];
void printTuple(const std::tuple<int,int,int>& ts)
{
std::cout << std::get<0>(ts) << "," <<
std::get<1>(ts) << "," <<
std::get<2>(ts) << "\n";
}
// Initialize the tuple set with the 3 column 2D array of items
void initializeTuple(int pArray[][3], int numItems, TupleSet& ts)
{
for (int i = 0; i < numItems; i)
ts.insert({pArray[i][0], pArray[i][1], pArray[i][2]});
}
int main()
{
// Assume that A, B, C, and D have been filled in with data
//...
static constexpr char *arrayName = "ABC";
// Declare an array of 3 tuple sets that represent A,B,C
std::array<TupleSet, 3> allTuples;
// This is for the "special" D Array
TupleSet tD;
//Store the data in the tuples
initializeTuple(A, 1000, allTuples[0]);
initializeTuple(B, 1000, allTuples[1]);
initializeTuple(C, 1000, allTuples[2]);
initializeTuple(D, 57100, tD);
// Now go through each tuple in D to see if it's
// in A, B, or C
for (auto& t : tD)
{
// print the tuple we're searching for
printTuple(t);
// Now see if it's in A, B, or C
for (int i = 0; i < 3; i)
{
auto iter = allTuples[i].find(t);
if ( iter != allTuples[i].end() )
{
std::cout << "Found a match in Array " <<
arrayName[i] << "\n";
break;
}
}
}
}
注意每個二維陣列是如何放置在一個元組集中的。此外,由于 astd::set不存盤重復項,因此該D陣列在放入元組 set 時將洗掉其所有重復項tD。因此,在那里,D代表的專案數量將被最小化。
但是,您應該注意一些問題:
元組的初始設定時間是該解決方案的一部分。然而,設定時間只進行一次。
使用 a 可能更快
std::unordered_set,但這需要你撰寫一個哈希函式,我把它作為練習留給你。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/494100.html
上一篇:C 11:如何使用lambda作為型別引數,它需要像std::less/std::greater這樣的“函子型別”?
下一篇:特征替換矩陣錯誤中的第一行:不匹配的型別'constEigen::ArrayBase<ExponentDerived>'和'int'
