Передача Boost :: Unordomed_set в качестве карты результатов для Boost :: Split

StackOverflow https://stackoverflow.com/questions/3981123

Вопрос

Кто -нибудь знает, является ли кошерным передать Boost :: Unomordered_set в качестве первого параметра для Boost :: Split? При Libbubost1.42-Dev это, похоже, вызывает проблемы. Вот небольшая программа, которая вызывает проблему, назовите ее test-split.cc:

#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/unordered_set.hpp>
#include <string>

int main(int argc, char **argv) {
  boost::unordered_set<std::string> tags_set;
  boost::split(tags_set, "a^b^c^",
               boost::is_any_of(std::string(1, '^')));
  return 0;
}

Затем, если я запускаю следующие команды:

g++ -o test-split test-split.cc; valgrind ./test-split

Я получаю кучу жалоб в Валгринд, подобных тем, которая следует за следующим (я также иногда вижу coredumps без Valgrind, хотя, кажется, варьируется в зависимости от времени):

==16843== Invalid read of size 8
==16843==    at 0x4ED07D3: std::string::end() const (in /usr/lib/libstdc++.so.6.0.13)
==16843==    by 0x401EE2: unsigned long boost::hash_value<char, std::allocator<char> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) (in /tmp/test-split)
...
==16843==    by 0x402248: boost::unordered_set<std::string, boost::hash<std::string>, std::equal_to<std::string>, std::allocator<std::string> >& boost::algorithm::split<boost::unordered_set<std::string, boost::hash<std::string>, std::equal_to<std::string>, std::allocator<std::string> >, char const [26], boost::algorithm::detail::is_any_ofF<char> >(boost::unordered_set<std::string, boost::hash<std::string>, std::equal_to<std::string>, std::allocator<std::string> >&, char const (&) [26], boost::algorithm::detail::is_any_ofF<char>, boost::algorithm::token_compress_mode_type) (in /tmp/test-split)
==16843==    by 0x40192A: main (in /tmp/test-split)
==16843==  Address 0x5936610 is 0 bytes inside a block of size 32 free'd
==16843==    at 0x4C23E0F: operator delete(void*) (vg_replace_malloc.c:387)
==16843==    by 0x4ED1EE8: std::basic_string<char, std::char_traits<char>, std::allocator<char> >::~basic_string() (in /usr/lib/libstdc++.so.6.0.13)
==16843==    by 0x404A8B: void boost::unordered_detail::hash_unique_table<boost::unordered_detail::set<boost::hash<std::string>, std::equal_to<std::string>, std::allocator<std::string> > >::insert_range_impl<boost::transform_iterator<boost::algorithm::detail::copy_iterator_rangeF<std::string, char const*>, boost::algorithm::split_iterator<char const*>, boost::use_default, boost::use_default> >(std::string const&, boost::transform_iterator<boost::algorithm::detail::copy_iterator_rangeF<std::string, char const*>, boost::algorithm::split_iterator<char const*>, boost::use_default, boost::use_default>, boost::transform_iterator<boost::algorithm::detail::copy_iterator_rangeF<std::string, char const*>, boost::algorithm::split_iterator<char const*>, boost::use_default, boost::use_default>) (in /tmp/test-split)
...
==16843==    by 0x402248: boost::unordered_set<std::string, boost::hash<std::string>, std::equal_to<std::string>, std::allocator<std::string> >& boost::algorithm::split<boost::unordered_set<std::string, boost::hash<std::string>, std::equal_to<std::string>, std::allocator<std::string> >, char const [26], boost::algorithm::detail::is_any_ofF<char> >(boost::unordered_set<std::string, boost::hash<std::string>, std::equal_to<std::string>, std::allocator<std::string> >&, char const (&) [26], boost::algorithm::detail::is_any_ofF<char>, boost::algorithm::token_compress_mode_type) (in /tmp/test-split)
==16843==    by 0x40192A: main (in /tmp/test-split)

Это коробка Debian Squeeze; Вот моя соответствующая информация о системе:

$ g++ --version
g++ (Debian 4.4.5-2) 4.4.5
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ dpkg -l | grep boost
ii  libboost-iostreams1.42.0            1.42.0-4                     Boost.Iostreams Library
ii  libboost1.42-dev                    1.42.0-4                     Boost C++ Libraries development files
$ uname -a
Linux gcc44-buildvm 2.6.32-5-amd64 #1 SMP Fri Sep 17 21:50:19 UTC 2010 x86_64 GNU/Linux

Тем не менее, код, похоже, работает нормально, если я понизите Libboost1.42-Dev до Libboost1.40-Dev. Так что это ошибка в Boost 1.42, или я неправильно использую Boost :: разделен, проходя в контейнере, который не может обрабатывать последовательности? Спасибо!

Это было полезно?

Решение

Это было подтверждено в списке рассылки USERS-USERS как ошибка в реализации Boost :: Unoromeded_Set. В списке рассылки доступно патч, и в ближайшее время будет зарегистрировано исправление, надеюсь, к тому времени, когда к Boost 1.45.

Пользователи повышения: патч

Пользователи повышения: подтверждение

Спасибо всем за то, что изучили это!

Другие советы

Я думаю, что ответ должен быть да.

Чтение заголовков (split.hpp и iter_find.hpp) split принимает SequenceSequenceT& Result как его первый аргумент, который он передает iter_split Какой диапазон создает его от двух boost::transform_iteratorS:

SequenceSequenceT Tmp(itBegin, itEnd);
Result.swap(Tmp);
return Result;

Таким образом, все, что ему нужно такого типа, - это то, что он имеет конструктор, который берет пару итераторов, которые обращаются за std::string (или, технически, для Boost_string_typename). И имеет член .swap () .. и имеет SequenceSequenceT::iterator Тип которого тип std::string.

доказательство:

#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <string>
#include <iterator>
#include <algorithm>
#include <iostream>
struct X
{
   typedef std::iterator<std::forward_iterator_tag,
           std::string, ptrdiff_t, std::string*, std::string&>
           iterator;
   X() {}
   template<typename Iter> X(Iter i1, Iter i2)
   {
       std::cout << "Constructed X: ";
       copy(i1, i2, std::ostream_iterator<std::string>(std::cout, " " ));
       std::cout << "\n";
   }
   void swap(X&) {}
};
int main()
{
  X x;
  boost::split(x, "a^b^c^", boost::is_any_of(std::string(1, '^')));
}

я так думаю unordered_set<std::string> должен удовлетворить эти требования.

Видимо, ответ нет да.

Используя следующий код, я получаю предупреждения о времени компиляции и утверждение времени выполнения (Visual C ++ V10) в unordered_set в то время как vector работает нормально (кроме пустой строки в последнем элементе, из -за следа «^»).

boost::unordered_set<std::string> tags_set;
vector<string> SplitVec; // #2: Search for tokens
boost::split( SplitVec, "a^b^c^", boost::is_any_of("^") ); 
boost::split( tags_set, "a^b^c^", boost::is_any_of("^") );

Совместимость итератора между источником (string) и целевой контейнер является проблемой. Я бы опубликовал ошибку предупреждения, но это одно из тех предупреждений о шаблоне «войны и мира».

РЕДАКТИРОВАТЬ:

Это похоже на ошибку в повышении unordered_set? Когда я использую следующее, это работает, как и следовало ожидать:

std::unordered_set<std::string> tags_set_std;
boost::split( tags_set_std, string("a^b^c^"), boost::is_any_of(string("^")) );
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top