开发者

Help in interpreting a c++ method

开发者 https://www.devze.com 2023-03-13 16:59 出处:网络
I have the following c++ method: typedef unsigned long p3tOffsetType; p3tOffsetType buildString(std::string string)

I have the following c++ method:

typedef unsigned long p3tOffsetType;
p3tOffsetType buildString(std::string string)
{
    for (stringMap::const_iterator string_iterator = strings.begin(); string_iterator != strings.end(); ++string_iterator)
    {
        if (string_iterator->second == string)
            return string_iterator->first;
    }
    p3tOffsetType new_string_offset = string_offset;
    strings[string_offset] = string;
    string_offset += string.size() + 1;

    return new_string_offset;
}

What does the function do? I can 开发者_如何学Pythongive more of the code if needed. The code is a snippet from a P3T file packer found in the source P3TBuilder (version 2.7).

I need to know this because I am trying to


Assuming that strings is a map<p3tOffsetType, std::string> and that string_offset is initialized to zero, it seems to do the following: Imagine that you call the method a few times with, say, "Hello", "Hi", and "Hey", and that you would treat all these strings as C-strings and store them in the same char array. The array elements would then be {'H', 'e', 'l', 'l', 'o', '\0', 'H', 'i', '\0', 'H', 'e', 'y', '\0'}. The starting indices of the three strings are 0, 6, and 9, respectively. What the method does is to create a map that maps these starting indices to the strings, so strings[0] == "Hello", strings[6] == "Hi", and strings[9] == "Hey". Also, it eliminates duplicates, so calling the method again with "Hello" would leave the map unchanged.


It iterates over strings which is a map from p3tOffsetType to string. If the sought after string is found in the map then it returns the offset. If not then it stores the string with the current offset as key and adds the length of the string to the global variable string_offset (which I assume initialized to zero).

Basically, a map of strings and their offsets is built. So if you called it with "Hello", "test" and "bla" it would contain the following:

strings[0] = "Hello"
strings[6] = "test"
strings[11] = "bla"

This keeps track of the strings and where they are located in the "bigger" string, so to speak.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号