在带有std :: vector的unsigned字符的typedef数组之间没有已知的转换

时间:2014-12-13 17:04:05

标签: c++ arrays vector

我正在尝试将类型定义的无符号字符数组推送到向量中,但它不会让我一直说no known conversion from unsigned char* to const unsigned char &[13]

实际的错误讯息:error: no matching function for call to ‘std::vector<unsigned char [13]>::push_back(unsigned char*&)’|

Typedef代码:

const int BYTE_STRING_LEN = 13;
typedef unsigned char byte;
typedef byte bytestring[BYTE_STRING_LEN];

添加到矢量代码:

void printNewSolution(bytestring b)
{
    // check against known solutions to see if it's unique
    static std::vector<bytestring> KnownSolutions;
    KnownSolutions.push_back(b);
}

编辑1: 我需要使用原始字符数组,因为我对它们进行按位操作,每个值需要1个字节。

1 个答案:

答案 0 :(得分:1)

这是怎么回事?

#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>

const int BYTE_STRING_LEN = 13;
typedef unsigned char byte;

struct bytestring
{
    bytestring(const byte* val)
    {
        memcpy(value, val, sizeof(value));
    }

    bool operator==(const bytestring& other) const
    {
        return memcmp(value, other.value, sizeof(value)) == 0;
    }

    byte value[BYTE_STRING_LEN];
};

void printNewSolution(bytestring b)
{
    // check against known solutions to see if it's unique
    static std::vector<bytestring> KnownSolutions;
    if (std::find(KnownSolutions.begin(), KnownSolutions.end(), b) == KnownSolutions.end())
    {
        std::cout << "new" << std::endl;
        KnownSolutions.push_back(b);
    }
    else
        std::cout << "old" << std::endl;
}

那里的输出声明只是为了表明它正在发挥作用。

此处可运行: http://coliru.stacked-crooked.com/a/09b6c0ac9889787a

有了这个解决方案,值得注意的是std::string只是

typedef basic_string<char> string;

因此,如果您想确保使用无符号字符,则可以使用

typedef std::basic_string<byte> bytestring;

此时剩下的仍然有效:

http://coliru.stacked-crooked.com/a/b2c5045be3deedf2