簡體   English   中英

在std :: vector中找到Iterator

[英]Find Iterator in a std::vector

我遇到問題,我正在嘗試創建一個用於讀寫.ini文件的系統,但我一直堅持如何正確添加節/鍵。 我以為可以將它們作為對象添加到std :: vector中,所以我編寫了以下代碼段(刪除了不相關的代碼):

// .h

class Ini
{
public:
    class IniSection
    {
        friend class Ini;

    private:
        IniSection(Ini *ini, std::string section);
        ~IniSection();

    private: 
        Ini *pIni;
        std::string sectionName;
    };

    vector<IniSection *>::iterator Ini::FindSection(std::string section);

    IniSection *AddSection(std::string name);

private:
    vector<IniSection *> Sections;
};

typedef Ini::IniSection IniSection;



// .cpp


IniSection::IniSection(Ini *ini, std::string section) : pIni(ini), sectionName(section)
{

}

vector<IniSection *>::iterator Ini::FindSection(std::string section)
{
    IniSection tempSection(NULL, section);

    return find(Sections.begin(), Sections.end(), tempSection); // ERROR
}

IniSection *Ini::AddSection(std::string name)
{
    vector<IniSection *>::const_iterator iter = FindSection(name);

    if (iter == Sections.end())
    {
        IniSection *newSection = new IniSection(this, name);
        Sections.push_back(newSection);
        return newSection;
    }
    else
        return *iter;
}

如您所見,我用

//錯誤

這是因為當我嘗試構建它時,出現此錯誤:

錯誤C2679二進制'==':未找到采用'const Ini :: IniSection'類型的右側操作數的運算符(或沒有可接受的轉換)

它出現在算法庫中。 所以我想我嘗試獲得迭代器的方式是錯誤的,所以也許有人可以幫助我。 我在互聯網上找不到適合我的東西。 提前致謝!

您需要在您的類IniSection添加一個operator==以回答問題“ IniSection 2個實例IniSection相等?”。 像這樣:

bool operator==(const IniSection& lhs, const IniSection& rhs)
{
   return (lhs.sectionName == rhs.sectionName);
}

上面的代碼有幾個問題。 如建議的那樣,您需要為IniSection定義一個operator == ,以便std::find能夠比較Sections向量中的條目。 但是,還有另一個問題: FindSection有點用處,因為您無法測試迭代器是否在Sections::end()處返回了點,因為Sections是私有成員。 如果我建議,您需要添加類似hasSection方法的方法,該方法返回bool ,並使用該方法測試是否存在節。 我隨意修改代碼來說明要點,可以根據需要隨意更改。

main.hpp

#ifndef MAIN_HPP
#define MAIN_HPP

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

class Ini
{
public:
    class IniSection
    {
        friend class Ini;

        Ini& pIni;
        std::string sectionName;
    public:
        IniSection(Ini& ini, const std::string& section);

        friend bool operator == (const IniSection& _this, const IniSection& _other)
        {
            return _this.sectionName == _other.sectionName;
        }
    };

    std::vector<IniSection>::iterator FindSection(const std::string& section);

    std::vector<IniSection>::iterator AddSection(const std::string& section);

    bool hasSection(const std::string& section);

    std::vector<std::string> sectionNames();

private:
    std::vector<IniSection> Sections;
};

typedef Ini::IniSection IniSection;


#endif // MAIN_HPP

main.cpp

#include "main.hpp"


IniSection::IniSection(Ini& ini, const std::string& section)
    :
      pIni(ini),
      sectionName(section)
{}

std::vector<IniSection>::iterator Ini::FindSection(const std::string& section)
{
    IniSection tempSection(*this, section);
    return std::find(Sections.begin(), Sections.end(), tempSection);
}

std::vector<IniSection>::iterator Ini::AddSection(const std::string& section)
{
    std::vector<IniSection>::iterator iter = FindSection(section);

    if (iter == Sections.end())
    {
        Sections.emplace_back(*this, section);
        return Sections.end() - 1;
    }
    else
    {
        return iter;
    }
}

bool Ini::hasSection(const std::string& section)
{
    return FindSection(section) != Sections.end();
}

std::vector<std::string> Ini::sectionNames()
{
    std::vector<std::string> names;
    for (const auto& s : Sections)
    {
        names.push_back(s.sectionName);
    }
    return names;
}

int main()
{
    Ini ini;

    ini.AddSection("Section1");
    ini.AddSection("Section2");
    ini.AddSection("Section3");

    if (ini.hasSection("Section1"))
    {
        std::cout << "Ini contains section 1!\n";
    }

    if (!ini.hasSection("Section4"))
    {
        std::cout << "Adding section 4...\n";
        ini.AddSection("Section4");
    }

    std::cout << "Ini contains the following sections:\n";
    for (const auto& s : ini.sectionNames())
    {
        std::cout << "\t" << s << "\n";
    }

    return 0;
}

打印:

Ini contains section 1!
Adding section 4...
Ini contains the following sections:
    Section1
    Section2
    Section3
    Section4

另外,如注釋中所建議, std::unordered_map是出色的執行程序,非常適合此類情況。

PS:您可能已經注意到,我用對象替換了原始指針。 std::vector這樣的STL容器在內部處理分配和釋放,因此不需要使用原始指針。

編輯

我已經修改了pastebin中的代碼,但是缺少了一些東西(我不確定IniPath是什么類型-也許是std::string嗎?)。 有很多改進的余地,例如,您可以在getSection中添加幾行以自動添加一個節(如果該節不存在)(因此您不必首先使用hasSection檢查是否存在)。 如前所述,您可以從使用std::unordered_map受益匪淺,因為插入,刪除和查找均攤銷了固定時間。 使用std::vector ,查找和檢索元素將是線性時間。 我不清楚有關的另一件事就是為什么你需要存儲的引用(或在原始代碼的指針)的父對象(如IniSection&內部IniKey )。 據我所知,您沒有使用這些。 只要您不存儲原始指針,就不需要實現自己的析構函數。

免責聲明:我尚未編譯和測試此代碼。

PS:您可能需要將此代碼發布在CodeReview上以進行進一步的改進。

main.hpp

#include <vector>
#include <string>
#include <fstream>
#include <algorithm>

class Ini
{

public:

    Ini();
    ~Ini();

    bool Load(std::string path);

    void Load(std::istream& input);

    bool Save(std::string path);

    void Save(std::ostream& output);

    void Create(std::string path);

    class IniSection
    {
        friend class Ini;

        Ini& pIni;
        std::string sectionName;

    public:
        IniSection(Ini& ini, const std::string& section);
        ~IniSection();

        friend bool operator == (const IniSection& _this, const IniSection& _other)
        {
            return _this.sectionName == _other.sectionName;
        }


        std::string GetSectionName();

        class IniKey
        {
            friend class IniSection;

            IniSection& pSection;
            std::string keyName;
            std::string keyValue;
            std::string commentValue;

        public:
            IniKey(IniSection& section, const std::string& key);
            ~IniKey();

            friend bool operator == (const IniKey& _this, const IniKey& _other)
            {
                return _this.keyName == _other.keyName;
            }

            void SetValue(std::string value);

            std::string GetValue();

            std::string GetKeyName();

            void AddComment(std::string comment);

            std::string GetComment();
        };

        void RemoveAllKeys();

        std::vector<IniKey>::iterator FindKey(const std::string& key);

        std::vector<IniKey>::iterator AddKey(const std::string& key);

        std::vector<IniKey>::iterator GetKey(const std::string& key);

        bool hasKey(const std::string& key);

        std::string GetKeyValue(const std::string& key);

        void SetKeyValue(const std::string& key, const std::string& value);

    private:
        std::vector<IniKey> Keys;
    };

    void RemoveAllSections();

    std::vector<IniSection>::iterator FindSection(const std::string& section);

    std::vector<IniSection>::iterator AddSection(const std::string& section);

    std::vector<IniSection>::iterator GetSection(const std::string& section);

    bool hasSection(const std::string& section);

    std::string GetKeyValue(std::string section, std::string key);

    void SetKeyValue(std::string section, std::string key, std::string value);

private:
    std::vector<IniSection> Sections;
};

typedef Ini::IniSection IniSection;
typedef IniSection::IniKey IniKey;

main.cpp

#include "main.hpp"

bool Ini::Load(std::string path)
{
    std::ifstream input;

    input.open(path.c_str(), std::ios::binary);

    if (!input.is_open())
        return false;

    Load(input);

    input.close();

    return true;
}

void Ini::Load(std::istream& input)
{
    std::vector<IniSection>::iterator section;
    std::string lineValue;

    enum
    {
        KEY,
        SECTION,
        COMMENT,
        OTHER
    };

    while (getline(input, lineValue))
    {
//      TrimLeft(lineValue);
//      TrimRight(lineValue, "\n\r");

        if (!lineValue.empty())
        {
            unsigned int type = OTHER;

            type = (lineValue.find_first_of("[") == 0 && (lineValue[lineValue.find_last_not_of(" \t\r\n")] == ']')) ? SECTION : OTHER;
            type = ((type == OTHER) && (lineValue.find_first_of("=") != std::string::npos && lineValue.find_first_of("=") > 0)) ? KEY : type;
            type = ((type == OTHER) && (lineValue.find_first_of("#") == 0)) ? COMMENT : type;

            switch (type)
            {
            case SECTION:
                section = AddSection(lineValue.substr(1, lineValue.size() - 2));
                break;
            case KEY:
                {
                    size_t equalSpot = lineValue.find_first_of("=");
                    std::string keyName = lineValue.substr(0, equalSpot);
                    std::string keyValue = lineValue.substr(equalSpot + 1);
                    std::vector<IniKey>::iterator key = section->AddKey(keyName);
                    key->SetValue(keyValue);
                    break;
                }

            default:
                break;
            }
        }
    }
}

void Ini::Create(std::string path)
{
    std::fstream file;

    file.open(path, std::fstream::out);

    file.close();
}

bool Ini::Save(std::string path)
{
    std::ofstream output;

    output.open(path.c_str(), std::ios::binary);

    if (!output.is_open())
    {
        output.close();

        return false;
    }

    Save(output);

    output.close();

    return true;
}

void Ini::Save(std::ostream& output)
{
    std::string section;
    std::vector<IniSection>::iterator iter1;

    for (iter1 = Sections.begin(); iter1 != Sections.end(); iter1++)
    {
        section = "[" + iter1->GetSectionName() + "]";

        output << section << "\r\n";

        std::vector<IniKey>::iterator iter2;

        for (iter2 = iter1->Keys.begin(); iter2 != iter1->Keys.end(); iter2++)
        {
            std::string comment = "# " + iter2->GetComment();

            if (comment != "# ")
                output << comment << "\r\n";

            std::string key = iter2->GetKeyName() + "=" + iter2->GetValue();

            output << key << "\r\n";
        }

        output << "\r\n";
    }
}

std::string Ini::GetKeyValue(std::string section, std::string key)
{
    if (hasSection(section))
    {
        auto s = GetSection(section);
        if (s->hasKey(key))
        {
            return s->GetKey(key)->GetValue();
        }
    }
    return std::string();
}

void Ini::SetKeyValue(std::string section, std::string key, std::string value)
{
    if (hasSection(section))
    {
        auto s = GetSection(section);
        if (s->hasKey(key))
        {
            s->GetKey(key)->SetValue(value);
        }
    }
}

// IniSection -----------------------------------------------------------------------------------

IniSection::IniSection(Ini& ini, const std::string& section) : pIni(ini), sectionName(section)
{

}

void Ini::RemoveAllSections()
{
//  std::vector<IniSection *>::iterator iter;

//  for (iter = Sections.begin(); iter != Sections.end(); iter++)
//      delete *iter;

    Sections.clear();
}

std::vector<IniSection>::iterator Ini::FindSection(const std::string& section)
{
    IniSection tempSection(*this, section);

    return std::find(Sections.begin(), Sections.end(), tempSection);
}

std::vector<IniSection>::iterator Ini::AddSection(const std::string& section)
{
    std::vector<IniSection>::iterator iter = FindSection(section);

    if (iter == Sections.end())
    {
        Sections.emplace_back(*this, section);

        return Sections.end() - 1;
    }
    else
        return iter;
}

std::vector<IniSection>::iterator Ini::GetSection(const std::string& section)
{
    return FindSection(section);
}

std::string IniSection::GetSectionName()
{
    return sectionName;
}

std::string IniSection::GetKeyValue(const std::string& key)
{
    if (hasKey(key))
    {
        return GetKey(key)->GetValue();
    }
    return std::string();
}

void IniSection::SetKeyValue(const std::string& key, const std::string& value)
{
    if (hasKey(key))
        GetKey(key)->SetValue(value);
}

// IniKey -----------------------------------------------------------------------------------

void IniSection::RemoveAllKeys()
{
    //  std::vector<IniKey *>::iterator iter;

    //  for (iter = Keys.begin(); iter != Keys.end(); iter++)
    //      delete *iter;

    // std::vector manages the allocations automatically
    // as long as you are not using raw pointers
    Keys.clear();
}

std::vector<IniKey>::iterator IniSection::FindKey(const std::string& key)
{
    IniKey tempKey(*this, key);
    return std::find(Keys.begin(), Keys.end(), tempKey);
}

std::vector<IniKey>::iterator IniSection::AddKey(const std::string& key)
{
    if (hasKey(key))
    {
        return GetKey(key);
    }
    else
        return Keys.insert(Keys.end(), {*this, key});
}

bool IniSection::hasKey(const std::string& key)
{
    return FindKey(key) != Keys.end();
}

void IniKey::SetValue(std::string value)
{
    keyValue = value;
}

std::string IniKey::GetValue()
{
    return keyValue;
}

std::string IniKey::GetKeyName()
{
    return keyName;
}

std::vector<IniKey>::iterator IniSection::GetKey(const std::string& key)
{
    if (hasKey(key))
        return GetKey(key);

    return Keys.end();
}

bool Ini::hasSection(const std::string& section)
{
    return FindSection(section) != Sections.end();
}

void IniKey::AddComment(std::string comment)
{
    commentValue = comment;
}

std::string IniKey::GetComment()
{
    return commentValue;
}


int main()
{
    // How i want to use it:
    // Write:
    Ini ini;

    ini.Create(IniPath);

    ini.Load(IniPath);

    // Check if "Test" section exists and add it if it doesn't
    if (!ini.hasSection("Test"))
    {
        ini.AddSection("Test");
    }

    auto secTest(ini.GetSection("Test"));
    secTest->AddKey("Key1")->SetValue("KeyValue1");
    secTest->GetKey("Key1")->AddComment("This is a Test");

    ini.Save(IniPath);

    // Read:
    Ini ini1;

    ini1.Load(IniPath);

//  IniSection *Section = ini.GetSection("Test");

    if (ini1.hasSection("Test"))
    {
        if (ini1.GetSection("Test")->hasKey("Key1"))
        {
            std::string keyValue = ini.GetSection("Test")->GetKeyValue("Key1");
        }
    }

    return 0;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM