【问题标题】:How to find all indexes of vector<vector<int>> for the minimum first index如何找到 vector<vector<int>> 的所有索引以获得最小的第一个索引
【发布时间】:2017-05-10 06:23:53
【问题描述】:

我有一个未排序且包含重复元素的二维数据向量。

如何找到最小值和所有具有该值的索引?

例如,给定数据vector&lt;vector&lt;int&gt;&gt; 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 &lt; mySol.size() &amp;&amp; mySol[0][0] == mySol[i][0]; i++) { nShortest += 1;}。无需遍历所有向量。
  • 是的,第一个元素是求最小值的值,其他元素是坐标。另外,vector> 中的 mySol 实际上是由其他函数以某种“mySol.push_back() 方式构建的。

标签: c++ c++11


【解决方案1】:

感谢贾罗德!根据 Jarod 的想法,我将代码修改如下。使用简单的 min 并避免 find_if。这似乎更快,避免排序并找到最小值。

vector<vector<int>> mySol = {{3,1},{1,2},{4,5},{1,3},{1,2}};
auto minIt = std::min(mySol.begin(), mySol.end());
cout << (*minIt)[0] << endl;

int nShortest = 0;
for (auto it = mySol.begin(); it != mySol.end(); ++it) {
    if ((*it)[0] == (*minIt)[0]) ++nShortest;
}
cout << nShortest << " ";

for (auto it = mySol.begin(); it != mySol.end(); ++it) {
    if ((*it)[0] == (*minIt)[0]) {
        cout << (*it)[1] << " ";
    }
}

【讨论】:

  • std::min 并没有达到您的预期 Demo。你真的需要std::min_element。对于过滤,没问题,nShortest 是错误的,因为现在输入没有排序。
  • 你说得对,Jarod42。 “min”的行为不像我预期的那样,因此必须使用 min_element。
【解决方案2】:

你可以在线性时间内完成这项工作:

  • 首先找到最小值
  • 然后迭代最小值。

类似:

auto cmp = [](const auto& lhs, const auto& rhs) { return lhs[0] < rhs[0]; }
auto minIt = std::min_element(mySol.begin(), mySol.end(), cmp);
auto eqToMin = [&](const auto& value) { return (*minIt)[0] == value[0]; }

for (auto it = minIt; it != mySol.end(); it = std::find_if(it + 1, mySol.end(), eqToMin)) {
    std::cout << (*it)[1] << std::endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 2013-03-29
    • 2018-05-20
    • 2015-05-09
    • 2016-03-05
    相关资源
    最近更新 更多