адаптер итератора для повторения только значений на карте?
Вопрос
Я просто возвращаюсь к C ++ после пары лет работы над C #, а недавно и над Objective C.
Одна вещь, которую я делал раньше, - это запустить мой собственный адаптер итератора для std::map, который будет ссылаться только на часть значения, а не на пару ключ-значение.Это довольно распространенный и естественный поступок.C # предоставляет эту возможность со своими свойствами Keys и Values своего класса Dictionary.NSDictionary Objective-C, аналогично, имеет allKeys и allValues .
С тех пор как я был "в отъезде", Boost приобрел библиотеки Range и ForEach, которые я сейчас широко использую.Я задавался вопросом, есть ли между ними какое-нибудь средство сделать то же самое, но я ничего не смог найти.
Я подумываю о том, чтобы создать что-нибудь с помощью адаптеров итераторов Boost, но прежде чем я пойду по этому пути, я подумал, что хотел бы спросить здесь, знает ли кто-нибудь о таком средстве в Boost или где-нибудь еще готовом?
Решение
Я не думаю, что здесь есть что-то нестандартное.Вы можете использовать boost::make_transform .
template<typename T1, typename T2> T2& take_second(const std::pair<T1, T2> &a_pair)
{
return a_pair.second;
}
void run_map_value()
{
map<int,string> a_map;
a_map[0] = "zero";
a_map[1] = "one";
a_map[2] = "two";
copy( boost::make_transform_iterator(a_map.begin(), take_second<int, string>),
boost::make_transform_iterator(a_map.end(), take_second<int, string>),
ostream_iterator<string>(cout, "\n")
);
}
Другие советы
Заменяю предыдущий ответ, на случай, если кто-нибудь еще найдет это так же, как я.Начиная с версии boost 1.43, доступно несколько широко используемых адаптеров диапазона.В этом случае вам нужен boost::adaptors::map_values.Соответствующий пример:http://www.boost.org/doc/libs/1_46_0/libs/range/doc/html/range/reference/adaptors/reference/map_values.html#range.reference.adaptors.reference.map_values.map_values_example
Именно для этой цели существует адаптер диапазона наддува.Видишь http://www.boost.org/doc/libs/1_53_0/libs/range/doc/html/range/reference/adaptors/reference/map_values.html
(Этот пример взят оттуда)
int main(int argc, const char* argv[])
{
using namespace boost::assign;
using namespace boost::adaptors;
std::map<int,int> input;
for (int i = 0; i < 10; ++i)
input.insert(std::make_pair(i, i * 10));
boost::copy(
input | map_values,
std::ostream_iterator<int>(std::cout, ","));
return 0;
}
Продолжая ответ Дэвида, есть еще одна возможность поставить точку, создав производный класс из boost::transform_iterator .Я использую это решение в своих проектах:
namespace detail
{
template<bool IsConst, bool IsVolatile, typename T>
struct add_cv_if_c
{
typedef T type;
};
template<typename T>
struct add_cv_if_c<true, false, T>
{
typedef const T type;
};
template<typename T>
struct add_cv_if_c<false, true, T>
{
typedef volatile T type;
};
template<typename T>
struct add_cv_if_c<true, true, T>
{
typedef const volatile T type;
};
template<typename TestConst, typename TestVolatile, typename T>
struct add_cv_if: public add_cv_if_c<TestConst::value, TestVolatile::value, T>
{};
} // namespace detail
/** An unary function that accesses the member of class T specified in the MemberPtr template parameter.
The cv-qualification of T is preserved for MemberType
*/
template<typename T, typename MemberType, MemberType T::*MemberPtr>
struct access_member_f
{
// preserve cv-qualification of T for T::second_type
typedef typename detail::add_cv_if<
std::tr1::is_const<T>,
std::tr1::is_volatile<T>,
MemberType
>::type& result_type;
result_type operator ()(T& t) const
{
return t.*MemberPtr;
}
};
/** @short An iterator adaptor accessing the member called 'second' of the class the
iterator is pointing to.
*/
template<typename Iterator>
class accessing_second_iterator: public
boost::transform_iterator<
access_member_f<
// note: we use the Iterator's reference because this type
// is the cv-qualified iterated type (as opposed to value_type).
// We want to preserve the cv-qualification because the iterator
// might be a const_iterator e.g. iterating a const
// std::pair<> but std::pair<>::second_type isn't automatically
// const just because the pair is const - access_member_f is
// preserving the cv-qualification, otherwise compiler errors will
// be the result
typename std::tr1::remove_reference<
typename std::iterator_traits<Iterator>::reference
>::type,
typename std::iterator_traits<Iterator>::value_type::second_type,
&std::iterator_traits<Iterator>::value_type::second
>,
Iterator
>
{
typedef boost::transform_iterator<
access_member_f<
typename std::tr1::remove_reference<
typename std::iterator_traits<Iterator>::reference
>::type,
typename std::iterator_traits<Iterator>::value_type::second_type,
&std::iterator_traits<Iterator>::value_type::second
>,
Iterator
> baseclass;
public:
accessing_second_iterator():
baseclass()
{}
// note: allow implicit conversion from Iterator
accessing_second_iterator(Iterator it):
baseclass(it)
{}
};
Это приводит к еще более чистому коду:
void run_map_value()
{
typedef map<int, string> a_map_t;
a_map_t a_map;
a_map[0] = "zero";
a_map[1] = "one";
a_map[2] = "two";
typedef accessing_second_iterator<a_map_t::const_iterator> ia_t;
// note: specify the iterator adaptor type explicitly as template type, enabling
// implicit conversion from begin()/end()
copy<ia_t>(a_map.begin(), a_map.end(),
ostream_iterator<string>(cout, "\n")
);
}