繁体   English   中英

在C ++中替换集合的最佳方法

[英]Best way to replace a set in C++

我必须重构看起来像这样的旧代码(我不是一个非常熟练的C ++编码器)

 std::set<SomeObject>::iterator it = setobject.begin();

 do {
     it->setProperty1ToNextValue();
     it->getProperty2();
     it->getProperty3();
     it++ 
 } while (it != setobject.end());

基本上我想迭代集合的元素并获取和设置/更新它们的一些属性。 我不能使用原始集,因为我在此线程中描述的问题中运行该对象具有与成员函数对象类型不兼容的类型限定符是const

我正在考虑用dequeue替换set(它将涉及一些重写),因为我将能够在dequeue的每个元素上设置和获取属性。 这是一个好方法吗?

std::set工作原理是根据对象的<运算符保持所有项目的顺序。 你不能在你的对象上调用非const方法的原因是因为这些方法有可能改变你的对象< operator返回的值,因此在没有std::set知道的情况下有效地“重新排序”引擎下的std::set

虽然你还没有详细说明你想要为我们提供最好的答案,但这里有几种技术方法可以在你的集合上调用一些方法。 您可以使用const_cast来调用您确定不会修改密钥的方法。 或者您可以将项目放在向量中,调用可能修改“键”的方法,然后将它们放回原始集中。

// Example program
#include <iostream>
#include <string>
#include <set>
#include <algorithm>

class SomeObject
{
    std::string key;
    int         data;

public:
    SomeObject( const std::string& key_, int data_ ) : key( key_ ), data( data_ )
    {}

    // For a item to be in a set, it must have a "<" operator that tells it how to order it
    bool operator <( const SomeObject& rhs ) const
    {
        return key < rhs.key;   
    }

    void setKey( const std::string& key_ )
    {
        key = key_;   
    }

    void setData( int data_ )
    {
        data = data_;   
    }
};

int main()
{   
     std::set< SomeObject > setobject;
     setobject.insert( SomeObject("c", 1 ) );
     setobject.insert( SomeObject("a", 1 ) );
     setobject.insert( SomeObject("b", 1 ) );

     // internally, the set will keep everything in order "a", "b", "c"

     // option 1 - use const_cast (risky!)
     {
         std::set< SomeObject >::iterator it = setobject.begin();

         do {
             // const_cast< SomeObject& >( *it ).setKey( "d" );  bad idea, now the set is jacked up because its not in the right order
             const_cast< SomeObject& >( *it ).setData( 2 );
             it++;
         } while (it != setobject.end());
     }

     // option 2 - put the items in the vector, call the methods, then put them back in the original set
     {
         std::vector< SomeObject > tempVec( std::begin( setobject ), std::end( setobject ) );
         std::vector< SomeObject >::iterator it = tempVec.begin();
         do {
             it->setKey( "d" ); 
             it->setData( 2 );
             it++;
         } while (it != tempVec.end());

         std::set< SomeObject > newSet( std::begin( tempVec ), std::end( tempVec ) );
         std::swap( newSet, setobject );  // put the new items back in the original setobject
     }



}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM