有没有办法像在python中那样在c ++中为数组建立索引?

时间:2018-12-23 14:42:45

标签: c++11

为了写一个数据包嗅探器,我需要能够对数据包的字节进行索引。

我来自python,在python中,您可以很容易地在列表中建立索引,例如;

variable = data[2:5]. In c++ you can't do it like that.

这是我的代码段

void ethernet_frame(char raw_data[19]){

    struct ethernet{ 
        char dest_mac[6] = get_mac_addr(raw_data[:7]);
        char src_mac[6] = get_mac_addr(raw_data[7:14]);
        unsigned short proto  = proto[14:17]; 
    };
}

我希望可以使用替代方法或库来对数据包进行索引。

2 个答案:

答案 0 :(得分:1)

没有内置的方法可以执行此操作,但是C ++允许您创建抽象来实现目标。例如

void ethernet_frame(std::array<char, 19> raw_data)
{
    struct ethernet
    {
        std::array<char, 6> dest_mac;
        std::array<char, 6> src_mac;
    };

    ethernet e{slice<0, 7>(raw_data), slice<7, 14>(raw_data)};
}

slice与以下内容类似:

template <std::size_t Begin, std::size_t End, typename T>
auto slice(const T& range)
{
    constexpr auto count = End - Begin - 1;
    std::array<std::decay_t<decltype(*range.begin())>, count> result;
    std::copy(range.begin() + Begin, range.begin() + End, result.begin());
    return result;
}

答案 1 :(得分:0)

C ++不是Python。所以你不能这样编码。

您可能想使用指针算术(例如,如果 final Graph graph = new Graph(); final Node node1 = new Node(getNodeText()); final Node node2 = new Node(getNodeText()); final Node node3 = new Node(getNodeText()); final Node node4 = new Node(getNodeText()); final Node node5 = new Node(getNodeText()); final Node node6 = new Node(getNodeText()); final Node node8 = new Node(getNodeText()); final Node node7 = new Node(getNodeText()); final Node node9 = new Node(getNodeText()); final Node node10 = new Node(getNodeText()); final Node node11 = new Node(getNodeText()); final Node node12 = new Node(getNodeText()); graph.addEdge(node1, node2); graph.addEdge(node1, node3); graph.addEdge(node1, node4); graph.addEdge(node2, node5); graph.addEdge(node2, node6); graph.addEdge(node6, node7); graph.addEdge(node6, node8); graph.addEdge(node4, node9); graph.addEdge(node4, node10); graph.addEdge(node4, node11); graph.addEdge(node11, node12); 是某个raw_data+7,则使用raw_data

您可以使用iteratorsrange for。然后,您想像char*std::array那样使用containers

请花几天或几周时间阅读一本好书C++ programming book。我们在这里没有时间或空间。