【发布时间】:2017-05-10 06:23:53
【问题描述】:
我有一个未排序且包含重复元素的二维数据向量。
如何找到最小值和所有具有该值的索引?
例如,给定数据vector<vector<int>> mySol = {{3,1},{1,2},{4,5},{1,3},{1,2}},我想找到{1,2}、{1,3} 和{1,2},它们给出最小值1(基于第一个元素)和索引2、3 和2。
如何改进以下代码sn-p?对于大数据,下面的代码似乎很慢,因为sort:
vector<vector<int>> mySol = {{3,1},{1,2},{4,5},{1,3},{1,2}};
sort(mySol.begin(), mySol.end());
//print out shortest distance
cout << mySol[0][0] << endl;
//print out the number of shortest paths
int nShortest = 0;
for (int i = 0; i < mySol.size(); i++) {
if (mySol[0][0] == mySol[i][0])
nShortest += 1;
}
cout << nShortest << " ";
//print out y-coordinates of the shortest paths in increasing order
for (int i = 0; i < nShortest; i++) {
cout << mySol[i][1] << " ";
}
【问题讨论】:
-
你想只比较内部向量的第一个元素吗?
-
此外,您的所有内部向量的长度似乎都是 2。如果是这样,也许您不想为它们使用 std::vector。
-
您可以先将您的第一个循环更改为
for (int i = 0; i < mySol.size() && mySol[0][0] == mySol[i][0]; i++) { nShortest += 1;}。无需遍历所有向量。 -
是的,第一个元素是求最小值的值,其他元素是坐标。另外,vector
> 中的 mySol 实际上是由其他函数以某种“mySol.push_back() 方式构建的。