Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string to boost::uuid conversion

I've just started using boost in c++ and I just wanted to ask a couple of questions relating to uuids.

I am loading in a file which requires I know the uuids so I can link some objects together. For this reason, I'm trying to write my own uuids but I'm not sure if there's any special conditions for the strings etc as the strings I've been using (usually something basic) are not working. Can anyone point me in the right direction? I've tried using a string generator, but to no avail thus far so I'm assuming there's something wrong with my strings (which have currently just been random words).

Here's a short example kind of thing, can't give the real code:

void loadFiles(std::string xmlFile);

void linkObjects(custObj network)
{
    for (int i = 0; i < network->getLength(); i++)
    {
        network[i]->setId([boost::uuid]);  
        if (i > 0)
            network[i]->addObj(network[i-1]->getId());
    }
}
like image 665
user3353807 Avatar asked Feb 26 '14 01:02

user3353807


People also ask

Is boost UUID unique?

When UUIDs are generated by one of the defined mechanisms, they are either guaranteed to be unique, different from all other generated UUIDs (that is, it has never been generated before and it will never be generated again), or it is extremely likely to be unique (depending on the mechanism).

What is uuid in c++?

UUIDs are 128-bit identifiers that can be used to uniquely identify information without requiring central coordination. These are often used in Cassandra for primary and clustering keys.

What is lexical cast?

boost::lexical_cast is an alternative to functions like std::stoi(), std::stod(), and std::to_string(), which were added to the standard library in C++11. Now let see the Implementation of this function in a program. Examples: Conversion integer -> string string- > integer integer -> char float- > string.


1 Answers

I took your question as "I need a sample". Here's a sample that shows

  • reading
  • writing
  • generating
  • comparing

uuids with Boost Uuid.

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/lexical_cast.hpp>

using namespace boost::uuids;

int main()
{
    random_generator gen;

    for (int i = 0; i < 10; ++i)
    {
        uuid new_one = gen(); // here's how you generate one

        std::cout << "You can just print it: " << new_one << "; ";

        // or assign it to a string
        std::string as_text = boost::lexical_cast<std::string>(new_one);

        std::cout << "as_text: '" << as_text << "'\n";

        // now, read it back in:
        uuid roundtrip = boost::lexical_cast<uuid>(as_text);

        assert(roundtrip == new_one);
    }
}

See it Live On Coliru

like image 173
sehe Avatar answered Sep 20 '22 17:09

sehe