小编dsm*_*ith的帖子

使用boost :: range在C++中进行花式索引

我想使用boost :: range来实现类似于NumPy和Matlab中可用的"花式索引".具体来说,我想使用另一个容器的元素作为索引来选择一个可索引容器的某些元素.例如,可以在Python中执行以下操作:

>>> squares = numpy.arange(10)**2  # Step 1 - setup squares
>>> indices = numpy.array([1,3,4]) # Step 2 - setup indices
>>> squares[indices]               # Step 3 - fancy indexing
array([ 1, 9, 16])
Run Code Online (Sandbox Code Playgroud)

在C++中,使用boost :: range,我认为上面的代码看起来像这样:

#include "sampled.hpp"
#include <boost/assign/std/vector.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/range/counting_range.hpp>
#include <iostream>
#include <vector>

using namespace boost;
using namespace boost::adaptors;
using namespace boost::assign;
using namespace boost::lambda;
using namespace std;

int main(int argc, char** argv)
{
    // Step 1 - setup …
Run Code Online (Sandbox Code Playgroud)

c++ templates boost numpy boost-range

9
推荐指数
1
解决办法
1247
查看次数

在C++中迭代std :: map的键/值

我的问题是对这一点的略微概括.为了便于讨论,我将专注于迭代地图的键.我想有一个通用的辅助函数,key_iterator它接受一个map迭代器并返回一个map key迭代器.例如,以下代码:

#include "key_iterator.hpp"
#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>

int main(int argc, char** argv)
{
    std::map<std::string, int> m;
    m["One"] = 1;
    m["Two"] = 2;
    std::copy(key_iterator(m.begin()), key_iterator(m.end()), std::ostream_iterator<std::string>(std::cout, " "));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

应该产生以下输出:

One Two
Run Code Online (Sandbox Code Playgroud)

正如上面提到的问题的解决方案中所建议的那样,boost :: transform_iterator似乎是实现的适当起点key_iterator.我有一个针对key_iterator.hpp的中间解决方案:

#pragma once

#include <functional>
#include <map>
#include <boost/iterator/transform_iterator.hpp>

template <typename Key, typename Value>
class KeyGetter : public std::unary_function<std::pair<Key,Value>, Key>
{
public:
    const Key& operator()(const std::pair<Key,Value>& p) const {return p.first;}
};

template<typename Key, typename …
Run Code Online (Sandbox Code Playgroud)

c++ templates boost map

5
推荐指数
1
解决办法
2125
查看次数

提供equals()的替代方案?

假设我有一个叫做的类Number,我打算对Number对象进行大量的相等比较.我担心泛型Number::equals(Object o)方法的"开销"(类比较等).在这种情况下,提供诸如Number::isEqualTo(Number other)替代方法之类的方法是否有用Number::equals(Object o)?这是一种常见的模式吗?或者JVM目前是否已经足够好地优化,这样做没有优势?

这是一个代码示例:

public class Number {
    int _value;

    Number(int value) {
        _value = value;
    }

    @Override
    public boolean equals(final Object o) {
        if (o == this) return true;
        if (o == null) return false;
        if (o.getClass() != getClass()) return false;
        return isEqualTo((Number)o);
    }

    public boolean isEqualTo(final Number other) {
        return _value == other._value;
    }

    public static void main(String[] args) {
        Number one = new Number(1);
        Number two …
Run Code Online (Sandbox Code Playgroud)

java

2
推荐指数
1
解决办法
187
查看次数

标签 统计

boost ×2

c++ ×2

templates ×2

boost-range ×1

java ×1

map ×1

numpy ×1