如何通过变量值获得最小值组?

时间:2018-07-18 10:32:46

标签: c++

我是cpp的菜鸟,我想获得一些帮助,我想在包含这些对象列表的向量中选择最低值。选择聚合

class Label{
private:
    std::string lbl;
    int n;

public:

    int getN() const { return this->n; }
    std::string getlbl() const { return this->lbl; }

};

int main() {
    std::vector<Label> my_vect = {
    {"labl07", 0}, {"labl07", 0}, {"labl07", 0}, 
    {"labl07", 0}, {"labl07", 0}, {"labl02", 232}, 
    {"labl02", 232}, {"labl02", 233}, {"labl02", 234}, 
    {"labl02", 230}, {"labl02", 233}, {"labl02", 234}, 
    {"labl02", 229}, {"labl03", 379}, {"labl03", 377}, 
    {"labl03", 379}, {"labl03", 381}, {"labl03", 380}, 
    {"labl03", 377}, {"labl03", 381}, {"labl03", 372}
    };

    for(auto & v: my_vect)
    {
        cout <<"dis : "<< v.getlbl() <<" value " <<  v.getN() << endl;

    }
    return 0;
}

我希望这样做

dis : labl07 value 0
dis : labl02 value 229
dis : labl03 value 372

在下面的一些评论中,他们使用地图关联容器,我需要了解为什么使用向量容器。

5 个答案:

答案 0 :(得分:4)

在这种情况下,请尝试使用关联的容器映射,因为使用向量会更加复杂。

string labelN;

string val;
int number;

map<string, int> values;  

while (readingInput)  
{
  // input next line
  fileInput >> labelN >>  " ">> val>> "value " >> number;
  if (number> values[val])
  {
     values[val] = number;
   }
}

在阅读以下建议后。我已经编写了这段代码,除非有人编写出更好的代码,否则我认为它可以完成工作。因此,首先,您必须创建要添加到向量中的对象的构造函数。 其次,您必须添加一个函数,该函数将以聚合方式对向量进行排序,然后将结果插入到地图中。在代码的最后部分,我将结果推入矢量中,您可能会使用它。

#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;

class Label{
private:
    std::string lbl;
    int n;

public:
    Label(std::string sp, int np): lbl(sp), n(np) {}
    int getN() const { return this->n; }
    std::string getlbl() const { return this->lbl; }
    static bool sortByn( Label a, Label b )
    {
       if ( a.n < b.n ) return true;
       if ( a.n == b.n && a.lbl < b.lbl ) return true;
       return false;
    }

};

int main() {
    std::vector<Label> my_vect = {
    {"labl07", 0}, {"labl07", 0}, {"labl07", 0},
    {"labl07", 0}, {"labl07", 0}, {"labl02", 232},
    {"labl02", 232}, {"labl02", 233}, {"labl02", 234},
    {"labl02", 230}, {"labl02", 233}, {"labl02", 234},
    {"labl02", 229}, {"labl03", 379}, {"labl03", 377},
    {"labl03", 379}, {"labl03", 381}, {"labl03", 380},
    {"labl03", 377}, {"labl03", 381}, {"labl03", 372}
    };

    for(auto & v: my_vect)
    {
        cout <<"dis : "<< v.getlbl() <<" value " <<  v.getN() << endl;
    }

    map<string,int> smallest;
    string lbl;
    int n;

    for(auto & v: my_vect)
    {
        lbl = v.getlbl();
        n = v.getN();
        bool occurredBefore = smallest.count( lbl );
        if ( occurredBefore )
        {
         if ( n < smallest[lbl] ) smallest[lbl] = n;
        }
        else
        {
         smallest[lbl] = n;
        }
    }

   vector<Label> V;
   for ( auto e : smallest ) V.push_back( { e.first, e.second } );
   sort( V.begin(), V.end(), Label::sortByn );
   for ( Label L : V ) cout << L.getlbl() << '\t' << L.getN() << '\n';
}

答案 1 :(得分:3)

如@Aconcagua所建议,您可以使用自定义比较器对向量进行排序,以对向量的值进行排序:

[](Label const& x, Label const& y) { 
            return ((x.getlbl() < y.getlbl()) || 
                   ((x.getlbl() == y.getlbl()) && (x.getN() < y.getN()))); };

您还需要一个构造函数来构造将插入到向量中的对象:

Label(std::string label, int value) : lbl(label), n(value){}

,并且当您遍历所有值时,只要标签是另一个标签,就打印该元素。因此,代码如下所示:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

class Label{
private:
    std::string lbl;
    int n;

public:
    Label(std::string label, int value) : lbl(label), n(value){}
    int getN() const { return this->n; }
    std::string getlbl() const { return this->lbl; }

};

int main() {
    std::vector<Label> my_vect = {
    {"labl07", 0}, {"labl07", 0}, {"labl07", 0}, 
    {"labl07", 0}, {"labl07", 0}, {"labl02", 232}, 
    {"labl02", 232}, {"labl02", 233}, {"labl02", 234}, 
    {"labl02", 230}, {"labl02", 233}, {"labl02", 234}, 
    {"labl02", 229}, {"labl03", 379}, {"labl03", 377}, 
    {"labl03", 379}, {"labl03", 381}, {"labl03", 380}, 
    {"labl03", 377}, {"labl03", 381}, {"labl03", 372}
    };

    std::sort(my_vect.begin(), my_vect.end(), [](Label const& x, Label const& y) { 
        return ((x.getlbl() < y.getlbl()) || ((x.getlbl() == y.getlbl()) && (x.getN() < y.getN()))); });

    std::string labelToPrint;

    for(const auto& v: my_vect)
    {
        if (labelToPrint.compare(v.getlbl()) != 0)
        {
            std::cout <<"dis : "<< v.getlbl() <<" value " <<  v.getN() << std::endl;    
            labelToPrint = v.getlbl();  
        }
    }
    return 0;
}

答案 2 :(得分:1)

您可以使用多图进行此操作,请考虑以下示例(和注释)

#include<iostream>
#include<string>
#include<map>
#include<vector>
#include<algorithm>

struct x{
    std::string s_value;
    int i_value;
};

int main() {
    std::vector<x> v{
        {"01", 11},
        {"02", 9},
        {"03", 27},
        {"01", 3},
        {"02", 7},
        {"03", 34},
        {"01", 2},
        {"02", 6},
        {"03", 11},
    };
    // get unique keys
    std::vector<std::string> keys {};
    for(auto& x_value: v){
        // if key is not present in keys yet put it there
        if(std::find(keys.begin(),keys.end(), x_value.s_value) == keys.end()){
            keys.push_back(x_value.s_value);
        }
    }
    std::multimap<std::string, int> mmap;
    for(auto& x_value : v){
        //put values from vector into multimap
        mmap.insert( decltype(mmap)::value_type(x_value.s_value, x_value.i_value) );
    }

    for(auto& key : keys){
      // for each value we expect to be in multimap get range of values
      std::vector<int> values{};
      auto range = mmap.equal_range(key);
      // put vaules for range into vector
      for(auto i = range.first; i!= range.second; ++i){
          values.push_back(i->second);
      }
      // sort vector
      std::sort(values.begin(), values.end());
      // print the least value in range corresponding to key, if there was any
      if(!values.empty()){
        std::cout<<key<<" "<<values[0]<<std::endl;
      }
    }

    return 0;
}

答案 3 :(得分:1)

尽管asdoudanswer在技术上是正确的(请参考编辑,修订版3),但它使用多个映射查找,可以通过以下变体避免这种情况:

for(auto & v: my_vect)
{
    int n = v.getN();
    // pre-C++11 variant:
    //auto entry = smallest.insert(std::make_pair(v.getlbl(), n));
    // since C++11:
    auto entry = smallest.emplace(v.getlbl(), n);
    if(!entry.second)
    {
        if(n < entry.first->second)
            entry.first->second = n;
    }
}

进一步的改进:字符串尚未复制,实际上是不必要的,因为映射的生存期不长于包含字符串的向量。因此,如果返回lbl作为const引用,我们可以使用std::reference_wrapper<std::string>作为映射键(甚至可以使用具有适当的自定义比较器的char const*)。

答案 4 :(得分:0)

您可以使用range-v3库轻松完成此操作:

auto groups = my_vect | ranges::view::group_by(
   [](const Label& l1, const Label& l2){ return l1.getlbl() == l2.getlbl(); });

for (const auto & group : groups) {
   auto min = ranges::min(group,
      [](const Label& l1, const Label& l2){ return l1.getN() < l2.getN(); });

   std::cout << min.getlbl() << ": " << min.getN() << std::endl;
}

输出:

labl07: 0
labl02: 229
labl03: 372

请注意,为了获得更高的性能,getlbl()应该通过const引用返回。