【问题标题】:Generating Identification Number of String Bundle生成字符串束的标识号
【发布时间】:2018-12-07 11:01:58
【问题描述】:

假设您有一个名为bundle 的结构,它由string 对象组成。没有关于一个包将包含多少个字符串的准确信息,您需要为每个包生成标识号,以便区分它们。

例如,两个包有 5 个字符串对象,而这两个对象只有四个是通用的。

注意 1:我需要一个识别号,因为在此过程中我遇到了很多捆绑包,其中一些包具有完全相同的字符串。

注意 2:我在 c++ 上工作,据我所知,c++ 中没有 hashable 或类似的东西。

How can we generate identification number ?

我想到的唯一解决方案是将字符串对象连接成一个包。我认为没有其他解决方案。也许用另一种格式或数据结构表示字符串可以更容易生成 id。

【问题讨论】:

  • 不完全清楚是什么问题。如果您的“捆绑包”是std::vector<std::string>,那么您可能只需要使用它的operator==...您能显示一些代码吗?

标签: c++ string random hashable


【解决方案1】:

你可以使用static int counter:

#include <iostream>
static int counter = 0;
struct bundle
{
    bool operator==(bundle& other){ return this->id == other.id; }

    int id = counter++;
    std::string a, b, c, d, e;
};

int main()
{
    bundle b1, b2, b3, b4, b5;
    std::cout << b1.id << ' ' << b5.id << std::endl;    // 0 4
    std::cout << (b1 == b5) << std::endl;               // 0
    b1 = b5;
    std::cout << (b1 == b5) << std::endl;               // 1
    return 0;
}

【讨论】:

    猜你喜欢
    • 2015-07-28
    • 2013-04-09
    • 2017-10-20
    • 1970-01-01
    • 2015-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    相关资源
    最近更新 更多