привет, помоги с решение задачи по программированию на с++, можешь объяснить как это делать и дать теорию необходимую для написания этого кода
Duplication
Реализуйте две функции -- DeDuplicate и Duplicate
Функция DeDuplicate принимает vector<unique_ptr<string>> in и возвращает vector<shared_ptr<string>> out, такой что:
*in[i] == *out[i] -- значения объектов на i-й позициях совпадает.
Каждое уникальное значение создано только в одной копии и все ссылки ведут на него.
Функция Duplicate производит обратное преобразование.
Assistant
Для решения этой задачи мы будем работать с указателями в C++, а именно с unique_ptr и shared_ptr. Позвольте кратко разъяснить основные концепции, которые понадобятся для понимания и решения задачи:
Основы unique_ptr и shared_ptr
unique_ptr:
Это уникальный указатель, который управляет объектом так, чтобы не было двух unique_ptr, указывающих на один и тот же объект. Он предоставляет безопасное управление динамической памятью, исключая возникновение утечек при строгом соблюдении уникальности.
unique_ptr не может быть скопирован, но может быть перемещен.
shared_ptr:
Это умный указатель, который позволяет нескольким указателям владеть одним и тем же объектом. Когда последний shared_ptr, владеющий данным объектом, уничтожается, объект удаляется из памяти.
shared_ptr использует счетчик ссылок, чтобы управлять временем жизни объекта.
Теперь, давайте посмотрим на функции, которые нам необходимо реализовать:
Реализация DeDuplicate
Функция DeDuplicate должна преобразовать вектор из unique_ptr<string> в вектор из shared_ptr<string>, при этом каждая уникальная строка должна находиться только в одной копии в памяти, но может иметь несколько ссылок.
cpp
#include <vector>
#include <string>
#include <memory>
#include <unordered_map>
std::vector<std::shared_ptr<std::string>> DeDuplicate(std::vector<std::unique_ptr<std::string>> in) {
std::unordered_map<std::string, std::shared_ptr<std::string>> uniqueStrings;
std::vector<std::shared_ptr<std::string>> out;
for (auto& ptr : in) {
const std::string& str = *ptr;
if (uniqueStrings.find(str) == uniqueStrings.end()) {
// Создаем новую shared_ptr, если этой строки еще нет в map
uniqueStrings[str] = std::make_shared<std::string>(str);
}
// Добавляем ссылку на существующий объект в результат
out.push_back(uniqueStrings[str]);
}
return out;
}
Реализация Duplicate
Функция Duplicate должна производить обратное преобразование: из shared_ptr<string> в unique_ptr<string>. Так как во входном векторе могут быть несколько ссылок на одну и ту же строку, в выходном будет создано несколько unique_ptr, указывающих на отдельные копии строк.
cpp
#include <vector>
#include <string>
#include <memory>
std::vector<std::unique_ptr<std::string>> Duplicate(std::vector<std::shared_ptr<std::string>> in) {
std::vector<std::unique_ptr<std::string>> out;
for (const auto& ptr : in) {
// Создаем новую unique_ptr для каждой shared_ptr
out.push_back(std::make_unique<std::string>(*ptr));
}
return out;
}
Объяснение
DeDuplicate:
Используем unordered_map для хранения уникальных строк и их соответствующих shared_ptr.
Проходим по unique_ptr из входного вектора, получаем строку и проверяем, есть ли она в unordered_map. Если нет, то создаем новый shared_ptr и добавляем в карту. Независимо от этого, добавляем shared_ptr в выходной вектор.
Duplicate:
Проходим по вектору shared_ptr. Для каждой строки создаем новый unique_ptr, который будет хранить копию строки, и добавляем его в выходной вектор.
Эти функции обеспечивают требуемое преобразование соблюдая правила управления памятью и использованием умных указателей C++.
User
а почему мы используем именно unordered map? какие есть альтернативы для общего познания?
Assistant
Мы используем unordered_map в этой реализации для обеспечения быстрого поиска и вставки уникальных строк, хранящих их соответствующие shared_ptr.
Почему unordered_map?
Быстрота Операций: unordered_map обеспечивает амортизированную временную сложность O(1) для операций поиска, вставки и удаления. Это делается за счет использования хеш-таблиц.
Нет Необходимости в Порядке: В нашем случае нас интересует лишь наличие или отсутствие строки в контейнере, но не их порядок. Поэтому упорядоченность хранимых данных здесь не важна.
Альтернативы unordered_map
std::map:
Это ассоциативный контейнер на базе красно-черного дерева, который поддерживает автоматическую сортировку ключей.
Предоставляет поиск, вставку и удаление за логарифмическое время O(log n).
Подходит, если важен порядок элементов или если необходим доступ к элементам в отсортированном порядке.
std::set / std::unordered_set:
Эти контейнеры хранят только ключи и могут быть использованы для отслеживания уникальных значений без ассоциирования их с какими-либо конкретными объектами.
std::unordered_set работает быстро в плане поиска (O(1) амортизированно), как и unordered_map, но не хранит пары ключ-значение, только ключи, что делает его менее подходящим для нашей задачи.
std::vector или std::list:
Они могут быть использованы для хранения пар вручную. Придется вручную реализовать логику поиска уникальных строк, что будет приводить к линейной сложности (O(n)) для каждой вставки или поиска.
Когда использовать разные структуры?
unordered_map: Используйте для быстрого доступа и когда порядок не имеет значения.
map: Используйте, если необходимо поддерживать данные в отсортированном виде или если требуется поддерживать связь между ключами и значениями.
set / unordered_set: Используйте для хранения уникальных значений без пары ключ-значение.
Последовательные контейнеры (vector, list): Используются, когда важно сохранять последовательный порядок добавления или требуется последовательный доступ к элементам.
Таким образом, выбор структуры данных зависит от требований к производительности и конкретных нужд задачи. В нашем случае unordered_map предоставляет оптимальный баланс скорости и простоты для задач, связанных с проверкой уникальности и быстрым доступом.
User
можешь объяснить почему мы используем ссылки допустим у const std::string& str = *ptr;
Assistant
Использование ссылок в C++ позволяет более эффективно работать с данными, особенно когда речь идет о больших объектах, таких как строки (std::string). Давайте рассмотрим подробнее причину использования ссылок, как в примере с конструкцией const std::string& str = *ptr;.
Почему ссылки?
Эффективность:
Использование ссылки вместо создания копии позволяет избежать вызова конструктора копирования, что экономит время и память. Вместо того чтобы создавать новую строку и затем уничтожать её, мы просто используем ссылку на существующий объект.
Это особенно важно в случае больших строк или массивов, где операция копирования может быть дорогостоящей.
Безопасность:
В данном случае ссылка объявлена как const, что означает, что мы не можем изменять объект, на который она ссылается. Это дает уверенность, что данные останутся неизменными, и снижает риск ошибок в коде.
Использование const также позволяет разработчикам понимать, что эта ссылка предназначена только для чтения.
Семантика:
Ссылки могут сделать ваш код более читаемым и понятным, проясняя намерения разработчика. Они явно показывают, что функция или блок кода просто "смотрит" на данные без намерения их изменять.
В конкретной строке const std::string& str = *ptr;, мы разыменовываем unique_ptr<std::string> (*ptr), чтобы получить объект, на который он указывает (то есть std::string). Вместо создания новой копии этой строки, мы создаем ссылку str, которая позволяет безопасно работать с этими данными.
Когда использовать ссылки
Когда нужно передать большой объект в функцию, но не хотите его изменять: Используйте const Type& (например, const std::string&), чтобы избежать ненужного копирования.
Когда функция не должна владеть данными: Используйте ссылки, чтобы избежать изменения счетчика ссылок, если работа идет с shared_ptr, или чтобы разграничить владение в случае работы с unique_ptr.
Когда объект не должен быть nullptr: Ссылки в C++ не могут быть пустыми, что означает дополнительный уровень безопасности (хотя вы все равно должны быть уверены, что объект существовал на момент создания ссылки).
Таким образом, использование ссылок в C++ — это полезная практика, улучшающая производительность и читаемость кода, особенно при работе с большими или неизменяемыми данными.
User
вот мой код
#include
#include
#include
#include <unordered_map>
for (auto& temp : in) {
std::unique_ptr<std::string> x = std::make_unique<std::string>(*temp);
out.push_back(x);
}
}
а вот такие ошибки мне выдало при проверке
In file included from main.cpp:1:
task.h: In function 'std::vector<std::unique_ptr<std::__cxx11::basic_string > > Duplicate(std::vector<std::shared_ptr<std::__cxx11::basic_string > >)':
task.h:26:1: error: no return statement in function returning non-void [-Werror=return-type]
26 | }
| ^
In file included from /usr/include/c++/13/ext/alloc_traits.h:34,
from /usr/include/c++/13/bits/stl_uninitialized.h:64,
from /usr/include/c++/13/vector:65,
from task.h:1:
/usr/include/c++/13/bits/alloc_traits.h: In instantiation of 'static constexpr void std::allocator_traits<std::allocator<_Up> >::construct(allocator_type&, _Up*, _Args&& ...) [with _Up = std::unique_ptr<std::__cxx11::basic_string >; _Args = {const std::unique_ptr<std::__cxx11::basic_string<char, std::char_traits, std::allocator >, std::default_delete<std::__cxx11::basic_string<char, std::char_traits, std::allocator > > >&}; _Tp = std::unique_ptr<std::__cxx11::basic_string >; allocator_type = std::allocator<std::unique_ptr<std::__cxx11::basic_string > >]':
/usr/include/c++/13/bits/stl_vector.h:1283:30: required from 'constexpr void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::unique_ptr<std::__cxx11::basic_string >; _Alloc = std::allocator<std::unique_ptr<std::__cxx11::basic_string > >; value_type = std::unique_ptr<std::__cxx11::basic_string >]'
task.h:24:22: required from here
/usr/include/c++/13/bits/alloc_traits.h:539:28: error: no matching function for call to 'construct_at(std::unique_ptr<std::__cxx11::basic_string >(0)) _Tp) std::construct_at(_Tp*, _Args&& ...)'
94 | construct_at(_Tp* __location, _Args&&... __args)
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/stl_construct.h:94:5: note: template argument deduction/substitution failed:
/usr/include/c++/13/bits/stl_construct.h: In substitution of 'template<class _Tp, class ... _Args> constexpr decltype (::new(void*(0)) _Tp) std::construct_at(_Tp*, _Args&& ...) [with _Tp = std::unique_ptr<std::__cxx11::basic_string >; _Args = {const std::unique_ptr<std::__cxx11::basic_string<char, std::char_traits, std::allocator >, std::default_delete<std::__cxx11::basic_string<char, std::char_traits, std::allocator > > >&}]':
/usr/include/c++/13/bits/alloc_traits.h:539:21: required from 'static constexpr void std::allocator_traits<std::allocator<_Up> >::construct(allocator_type&, _Up*, _Args&& ...) [with _Up = std::unique_ptr<std::__cxx11::basic_string >; _Args = {const std::unique_ptr<std::__cxx11::basic_string<char, std::char_traits, std::allocator >, std::default_delete<std::__cxx11::basic_string<char, std::char_traits, std::allocator > > >&}; _Tp = std::unique_ptr<std::__cxx11::basic_string >; allocator_type = std::allocator<std::unique_ptr<std::__cxx11::basic_string > >]'
/usr/include/c++/13/bits/stl_vector.h:1283:30: required from 'constexpr void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::unique_ptr<std::__cxx11::basic_string >; _Alloc = std::allocator<std::unique_ptr<std::__cxx11::basic_string > >; value_type = std::unique_ptr<std::__cxx11::basic_string >]'
task.h:24:22: required from here
/usr/include/c++/13/bits/stl_construct.h:96:17: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = std::__cxx11::basic_string; _Dp = std::default_delete<std::__cxx11::basic_string >]'
96 | -> decltype(::new((void*)0) _Tp(std::declval<_Args>()...))
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/13/memory:78,
from task.h:3:
/usr/include/c++/13/bits/unique_ptr.h:522:7: note: declared here
522 | unique_ptr(const unique_ptr&) = delete;
| ^~~~~~~~~~
/usr/include/c++/13/bits/stl_uninitialized.h: In instantiation of 'constexpr bool std::__check_constructible() [with _ValueType = unique_ptr<__cxx11::basic_string >; _Tp = const unique_ptr<__cxx11::basic_string >&]':
/usr/include/c++/13/bits/stl_uninitialized.h:182:4: required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_uninitialized.h:373:37: required from 'constexpr _ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >; _Tp = unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_vector.h:603:31: required from 'constexpr std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::unique_ptr<std::__cxx11::basic_string >; _Alloc = std::allocator<std::unique_ptr<std::__cxx11::basic_string > >]'
main.cpp:42:35: required from here
/usr/include/c++/13/bits/stl_uninitialized.h:90:56: error: static assertion failed: result type must be constructible from input type
90 | static_assert(is_constructible<_ValueType, _Tp>::value,
| ^~~~~
/usr/include/c++/13/bits/stl_uninitialized.h:90:56: note: 'std::integral_constant<bool, false>::value' evaluates to false
/usr/include/c++/13/bits/stl_construct.h: In instantiation of 'constexpr void std::_Construct(_Tp*, _Args&& ...) [with _Tp = unique_ptr<__cxx11::basic_string >; _Args = {const unique_ptr<__cxx11::basic_string<char, char_traits, allocator >, default_delete<__cxx11::basic_string<char, char_traits, allocator > > >&}]':
/usr/include/c++/13/bits/stl_uninitialized.h:120:21: required from 'constexpr _ForwardIterator std::__do_uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_uninitialized.h:371:30: required from 'constexpr _ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >; _Tp = unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_vector.h:603:31: required from 'constexpr std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::unique_ptr<std::__cxx11::basic_string >; _Alloc = std::allocator<std::unique_ptr<std::__cxx11::basic_string > >]'
main.cpp:42:35: required from here
/usr/include/c++/13/bits/stl_construct.h:115:28: error: no matching function for call to 'construct_at(std::unique_ptr<std::__cxx11::basic_string >(0)) _Tp) std::construct_at(_Tp*, _Args&& ...)'
94 | construct_at(_Tp* __location, _Args&&... __args)
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/stl_construct.h:94:5: note: template argument deduction/substitution failed:
/usr/include/c++/13/bits/stl_construct.h: In substitution of 'template<class _Tp, class ... _Args> constexpr decltype (::new(void*(0)) _Tp) std::construct_at(_Tp*, _Args&& ...) [with _Tp = std::unique_ptr<std::__cxx11::basic_string >; _Args = {const std::unique_ptr<std::__cxx11::basic_string<char, std::char_traits, std::allocator >, std::default_delete<std::__cxx11::basic_string<char, std::char_traits, std::allocator > > >&}]':
/usr/include/c++/13/bits/stl_construct.h:115:21: required from 'constexpr void std::_Construct(_Tp*, _Args&& ...) [with _Tp = unique_ptr<__cxx11::basic_string >; _Args = {const unique_ptr<__cxx11::basic_string<char, char_traits, allocator >, default_delete<__cxx11::basic_string<char, char_traits, allocator > > >&}]'
/usr/include/c++/13/bits/stl_uninitialized.h:120:21: required from 'constexpr _ForwardIterator std::__do_uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_uninitialized.h:371:30: required from 'constexpr _ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >; _Tp = unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_vector.h:603:31: required from 'constexpr std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::unique_ptr<std::__cxx11::basic_string >; _Alloc = std::allocator<std::unique_ptr<std::__cxx11::basic_string > >]'
main.cpp:42:35: required from here
/usr/include/c++/13/bits/stl_construct.h:96:17: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = std::__cxx11::basic_string; _Dp = std::default_delete<std::__cxx11::basic_string >]'
96 | -> decltype(::new((void*)0) _Tp(std::declval<_Args>()...))
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/c++/13/bits/unique_ptr.h:522:7: note: declared here
522 | unique_ptr(const unique_ptr&) = delete;
| ^~~~~~~~~~
/usr/include/c++/13/bits/stl_construct.h: In instantiation of 'constexpr void std::_Construct(_Tp*, _Args&& ...) [with _Tp = unique_ptr<__cxx11::basic_string >; _Args = {const unique_ptr<__cxx11::basic_string<char, char_traits, allocator >, default_delete<__cxx11::basic_string<char, char_traits, allocator > > >&}]':
/usr/include/c++/13/bits/stl_uninitialized.h:120:21: required from 'constexpr _ForwardIterator std::__do_uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_uninitialized.h:371:30: required from 'constexpr _ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >; _Tp = unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_vector.h:603:31: required from 'constexpr std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::unique_ptr<std::__cxx11::basic_string >; _Alloc = std::allocator<std::unique_ptr<std::__cxx11::basic_string > >]'
main.cpp:42:35: required from here
/usr/include/c++/13/bits/stl_construct.h:119:7: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = std::__cxx11::basic_string; _Dp = std::default_delete<std::__cxx11::basic_string >]'
119 | ::new((void*)__p) _Tp(std::forward<_Args>(__args)...);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/c++/13/bits/unique_ptr.h:522:7: note: declared here
522 | unique_ptr(const unique_ptr&) = delete;
| ^~~~~~~~~~
cc1plus: all warnings being treated as errors
Assistant
Давайте разберем ошибки, которые вы получили, и исправим ваш код.
Ошибки
Отсутствие return в функции Duplicate:
В функции Duplicate у вас отсутствует оператор return. Функция, которая объявлена с возвращаемым типом non-void, должна возвращать значение типа, указанного в сигнатуре функции.
Ошибка копирования unique_ptr:
Основная ошибка возникает из-за попытки копирования unique_ptr, которая запрещена, так как unique_ptr является уникальным владельцем ресурса. Копирование unique_ptr недопустимо, а в out.push_back(x); у вас фактически происходит попытка копирования.
Исправление кода
Добавьте оператор return в функцию Duplicate.
При перемещении unique_ptr, вместо копирования используйте std::move, так как unique_ptr поддерживает перемещение, но не копирование.
Исправленный код будет выглядеть так:
cpp
#include <vector>
#include <string>
#include <memory>
#include <unordered_map>
std::vector<std::shared_ptr<std::string>> DeDuplicate(std::vector<std::unique_ptr<std::string>> in) {
std::vector<std::shared_ptr<std::string>> out;
std::unordered_map<std::string, std::shared_ptr<std::string>> proverka;
for (auto& temp : in) {
// Приводим unique_ptr к string и используем ссылку для работы с объектом.
const std::string& x = *temp;
if (proverka.find(x) == proverka.end()) {
proverka[x] = std::make_shared<std::string>(x);
}
out.push_back(proverka[x]);
}
return out;
}
std::vector<std::unique_ptr<std::string>> Duplicate(std::vector<std::shared_ptr<std::string>> in) {
std::vector<std::unique_ptr<std::string>> out;
for (const auto& temp : in) {
// Создаем уникальный указатель на копию строки и используем перемещение
std::unique_ptr<std::string> x = std::make_unique<std::string>(*temp);
out.push_back(std::move(x));
}
return out;
}
Объяснения
Использование std::move: Мы используем std::move, чтобы переместить unique_ptr в вектор out. Это позволяет передать владение от одной переменной к другой, что важно для правильного использования unique_ptr.
Исправление return в Duplicate: Обязательно добавляйте оператор return в функции, которые должны возвращать значение. Это исправит первую ошибку "no return statement in function returning non-void".
User
вот мой код
#include
#include
#include
#include <unordered_map>
for (auto& temp : in) {
//std::unique_ptr<std::string> x = std::make_unique<std::string>(*temp);
out.push_back(std::make_unique<std::string>(*temp));
}
return out;
}
вот такие ошибки мне выдает при проверке
In file included from /usr/include/c++/13/vector:65,
from task.h:1,
from main.cpp:1:
/usr/include/c++/13/bits/stl_uninitialized.h: In instantiation of 'constexpr bool std::__check_constructible() [with _ValueType = unique_ptr<__cxx11::basic_string >; _Tp = const unique_ptr<__cxx11::basic_string >&]':
/usr/include/c++/13/bits/stl_uninitialized.h:182:4: required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >, vector<unique_ptr<__cxx11::basic_string > > >; _ForwardIterator = unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_uninitialized.h:373:37: required from 'constexpr _ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >, vector<unique_ptr<__cxx11::basic_string > > >; _ForwardIterator = unique_ptr<__cxx11::basic_string >; _Tp = unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_vector.h:603:31: required from 'constexpr std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::unique_ptr<std::__cxx11::basic_string >; _Alloc = std::allocator<std::unique_ptr<std::__cxx11::basic_string > >]'
main.cpp:42:35: required from here
/usr/include/c++/13/bits/stl_uninitialized.h:90:56: error: static assertion failed: result type must be constructible from input type
90 | static_assert(is_constructible<_ValueType, _Tp>::value,
| ^~~~~
/usr/include/c++/13/bits/stl_uninitialized.h:90:56: note: 'std::integral_constant<bool, false>::value' evaluates to false
In file included from /usr/include/c++/13/bits/stl_iterator.h:85,
from /usr/include/c++/13/bits/stl_algobase.h:67,
from /usr/include/c++/13/vector:62:
/usr/include/c++/13/bits/stl_construct.h: In instantiation of 'constexpr void std::_Construct(_Tp*, _Args&& ...) [with _Tp = unique_ptr<__cxx11::basic_string >; _Args = {const unique_ptr<__cxx11::basic_string<char, char_traits, allocator >, default_delete<__cxx11::basic_string<char, char_traits, allocator > > >&}]':
/usr/include/c++/13/bits/stl_uninitialized.h:120:21: required from 'constexpr _ForwardIterator std::__do_uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_uninitialized.h:371:30: required from 'constexpr _ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >; _Tp = unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_vector.h:603:31: required from 'constexpr std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::unique_ptr<std::__cxx11::basic_string >; _Alloc = std::allocator<std::unique_ptr<std::__cxx11::basic_string > >]'
main.cpp:42:35: required from here
/usr/include/c++/13/bits/stl_construct.h:115:28: error: no matching function for call to 'construct_at(std::unique_ptr<std::__cxx11::basic_string >(0)) _Tp) std::construct_at(_Tp*, _Args&& ...)'
94 | construct_at(_Tp* __location, _Args&&... __args)
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/stl_construct.h:94:5: note: template argument deduction/substitution failed:
/usr/include/c++/13/bits/stl_construct.h: In substitution of 'template<class _Tp, class ... _Args> constexpr decltype (::new(void*(0)) _Tp) std::construct_at(_Tp*, _Args&& ...) [with _Tp = std::unique_ptr<std::__cxx11::basic_string >; _Args = {const std::unique_ptr<std::__cxx11::basic_string<char, std::char_traits, std::allocator >, std::default_delete<std::__cxx11::basic_string<char, std::char_traits, std::allocator > > >&}]':
/usr/include/c++/13/bits/stl_construct.h:115:21: required from 'constexpr void std::_Construct(_Tp*, _Args&& ...) [with _Tp = unique_ptr<__cxx11::basic_string >; _Args = {const unique_ptr<__cxx11::basic_string<char, char_traits, allocator >, default_delete<__cxx11::basic_string<char, char_traits, allocator > > >&}]'
/usr/include/c++/13/bits/stl_uninitialized.h:120:21: required from 'constexpr _ForwardIterator std::__do_uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_uninitialized.h:371:30: required from 'constexpr _ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >; _Tp = unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_vector.h:603:31: required from 'constexpr std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::unique_ptr<std::__cxx11::basic_string >; _Alloc = std::allocator<std::unique_ptr<std::__cxx11::basic_string > >]'
main.cpp:42:35: required from here
/usr/include/c++/13/bits/stl_construct.h:96:17: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = std::__cxx11::basic_string; _Dp = std::default_delete<std::__cxx11::basic_string >]'
96 | -> decltype(::new((void*)0) _Tp(std::declval<_Args>()...))
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/13/memory:78,
from task.h:3:
/usr/include/c++/13/bits/unique_ptr.h:522:7: note: declared here
522 | unique_ptr(const unique_ptr&) = delete;
| ^~~~~~~~~~
/usr/include/c++/13/bits/stl_construct.h: In instantiation of 'constexpr void std::_Construct(_Tp*, _Args&& ...) [with _Tp = unique_ptr<__cxx11::basic_string >; _Args = {const unique_ptr<__cxx11::basic_string<char, char_traits, allocator >, default_delete<__cxx11::basic_string<char, char_traits, allocator > > >&}]':
/usr/include/c++/13/bits/stl_uninitialized.h:120:21: required from 'constexpr _ForwardIterator std::__do_uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_uninitialized.h:371:30: required from 'constexpr _ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >; _Tp = unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_vector.h:603:31: required from 'constexpr std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::unique_ptr<std::__cxx11::basic_string >; _Alloc = std::allocator<std::unique_ptr<std::__cxx11::basic_string > >]'
main.cpp:42:35: required from here
/usr/include/c++/13/bits/stl_construct.h:119:7: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = std::__cxx11::basic_string; _Dp = std::default_delete<std::__cxx11::basic_string >]'
119 | ::new((void*)__p) _Tp(std::forward<_Args>(__args)...);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/c++/13/bits/unique_ptr.h:522:7: note: declared here
522 | unique_ptr(const unique_ptr&) = delete;
| ^~~~~~~~~~
Assistant
Ошибки, которые вы видите, связаны с попыткой копирования unique_ptr, что запрещено, так как unique_ptr предназначен для уникального владения объектом. Эти ошибки часто возникают из-за попыток использовать копирующие операции с unique_ptr.
Причины ошибки
unique_ptr не копируется:
В C++, конструктор копирования и оператор присваивания для unique_ptr удалены (= delete), чтобы избежать двойного удаления объекта.
В конструкторе std::vector происходит попытка копирования элементов, если вы пытаетесь создать вектор unique_ptr с использованием его конструктора копирования.
Решение
Из вашего кода кажется, что ошибка могла возникнуть из-за неявных операций копирования вектора, которые требуют копирования или эффективного переноса элементов, что unique_ptr не позволяет.
Ваша функция Duplicate на данный момент выглядит правильно, поскольку она создает новые уникальные указатели для каждой строки:
Проблема может быть вызвана неправильной копией вектора Duplicate или DeDuplicate. Убедитесь, что передаваемый параметр in в функции Duplicate не является const или другим вектором unique_ptr.
Проверка
Аккуратность с std::unique_ptr:
Убедитесь, что std::unique_ptr не копируется. Если вы используете в функции что-то вроде out.push_back(x);, тогда следует использовать std::move(x);.
Использование стандартных структур данных:
Убедитесь, что между вызовами функций не осуществляется неявная попытка копирования unique_ptr.
Обработка вектора:
Если используется промежуточный код (например, тестирование или иной код с использованием векторов), удостоверьтесь, что копирование unique_ptr не производится.
Желательно проверить, нет ли других мест в вашем кодовом проекте, где осуществляется цикл с перемещениями unique_ptr, или где Duplicate или DeDuplicate функции вызываются с неправильными аргументами. В вашем текущем коде проблема появляется в попытке осуществить копирование в векторе std::unique_ptr.
User
вот файл, который проверяет мой код, может исходя из него может будет более понятно где ошибка
#include "task.h"
#include
#include
#include
void TestDuplication() {
const auto first = std::make_sharedstd::string("first");
const auto second = std::make_sharedstd::string("second");
const auto third = std::make_sharedstd::string("third");
void TestDuplication2() {
const auto value = std::make_sharedstd::string("value");
const std::vector<std::shared_ptrstd::string> dedup {value ,value, value, value, value};
code
const auto dup = Duplicate(dedup);
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < i; ++j) {
assert(dup[i] != dup[j]);
}
}
for (int i = 0; i < 5; ++i) {
assert(*dup[i] == "value");
}
}
#include
void TestDeDuplication2() {
std::vector<std::unique_ptrstd::string> dup;
for (int i = 0; i < 5; ++i) {
dup.push_back(std::make_uniquestd::string("value"));
}
code
const auto dedup = DeDuplicate(dup);
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < i; ++j) {
assert(dedup[i] == dedup[j]);
}
}
for (int i = 0; i < 5; ++i) {
assert(*dedup[i] == "value");
}
}
int main() {
TestDuplication();
TestDeDuplication();
TestDuplication2();
TestDeDuplication2();
return 0;
}
Assistant
Согласно вашему описанию и предоставленному тестовому коду, задача состоит в том, чтобы корректно реализовать функции DeDuplicate и Duplicate, которые конвертируют данные между контейнерами std::vector с различными умными указателями. Давайте еще раз внимательно рассмотрим функции:
DeDuplicate:
Поскольку unique_ptr хранит уникальные строки, мы должны преобразовать их в shared_ptr, таким образом, чтобы каждая строка в выходном векторе ссылалась на один и тот же объект в памяти, если их значения совпадают.
Duplicate:
Для каждого shared_ptr во входном векторе необходимо создать новый unique_ptr, чтобы в выходном векторе каждая строка была уникальной в памяти.
Давайте еще раз проверим ваши текущие реализации функций:
проверь код по тестовому который я тебе скинул в прошлом сообщении и найди где ошибка, вот еще раз, то что выводит консоль
In file included from /usr/include/c++/13/vector:65,
from task.h:1,
from main.cpp:1:
/usr/include/c++/13/bits/stl_uninitialized.h: In instantiation of 'constexpr bool std::__check_constructible() [with _ValueType = unique_ptr<__cxx11::basic_string >; _Tp = const unique_ptr<__cxx11::basic_string >&]':
/usr/include/c++/13/bits/stl_uninitialized.h:182:4: required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >, vector<unique_ptr<__cxx11::basic_string > > >; _ForwardIterator = unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_uninitialized.h:373:37: required from 'constexpr _ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >, vector<unique_ptr<__cxx11::basic_string > > >; _ForwardIterator = unique_ptr<__cxx11::basic_string >; _Tp = unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_vector.h:603:31: required from 'constexpr std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::unique_ptr<std::__cxx11::basic_string >; _Alloc = std::allocator<std::unique_ptr<std::__cxx11::basic_string > >]'
main.cpp:42:35: required from here
/usr/include/c++/13/bits/stl_uninitialized.h:90:56: error: static assertion failed: result type must be constructible from input type
90 | static_assert(is_constructible<_ValueType, _Tp>::value,
| ^~~~~
/usr/include/c++/13/bits/stl_uninitialized.h:90:56: note: 'std::integral_constant<bool, false>::value' evaluates to false
In file included from /usr/include/c++/13/bits/stl_iterator.h:85,
from /usr/include/c++/13/bits/stl_algobase.h:67,
from /usr/include/c++/13/vector:62:
/usr/include/c++/13/bits/stl_construct.h: In instantiation of 'constexpr void std::_Construct(_Tp*, _Args&& ...) [with _Tp = unique_ptr<__cxx11::basic_string >; _Args = {const unique_ptr<__cxx11::basic_string<char, char_traits, allocator >, default_delete<__cxx11::basic_string<char, char_traits, allocator > > >&}]':
/usr/include/c++/13/bits/stl_uninitialized.h:120:21: required from 'constexpr _ForwardIterator std::__do_uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >, vector<unique_ptr<__cxx11::basic_string > > >; _ForwardIterator = unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_uninitialized.h:371:30: required from 'constexpr _ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >; _Tp = unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_vector.h:603:31: required from 'constexpr std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::unique_ptr<std::__cxx11::basic_string >; _Alloc = std::allocator<std::unique_ptr<std::__cxx11::basic_string > >]'
main.cpp:42:35: required from here
/usr/include/c++/13/bits/stl_construct.h:115:28: error: no matching function for call to 'construct_at(std::unique_ptr<std::__cxx11::basic_string >(0)) _Tp) std::construct_at(_Tp*, _Args&& ...)'
94 | construct_at(_Tp* __location, _Args&&... __args)
| ^~~~~~~~~~~~
/usr/include/c++/13/bits/stl_construct.h:94:5: note: template argument deduction/substitution failed:
/usr/include/c++/13/bits/stl_construct.h: In substitution of 'template<class _Tp, class ... _Args> constexpr decltype (::new(void*(0)) _Tp) std::construct_at(_Tp*, _Args&& ...) [with _Tp = std::unique_ptr<std::__cxx11::basic_string >; _Args = {const std::unique_ptr<std::__cxx11::basic_string<char, std::char_traits, std::allocator >, std::default_delete<std::__cxx11::basic_string<char, std::char_traits, std::allocator > > >&}]':
/usr/include/c++/13/bits/stl_construct.h:115:21: required from 'constexpr void std::_Construct(_Tp*, _Args&& ...) [with _Tp = unique_ptr<__cxx11::basic_string >; _Args = {const unique_ptr<__cxx11::basic_string<char, char_traits, allocator >, default_delete<__cxx11::basic_string<char, char_traits, allocator > > >&}]'
/usr/include/c++/13/bits/stl_uninitialized.h:120:21: required from 'constexpr _ForwardIterator std::__do_uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_uninitialized.h:371:30: required from 'constexpr _ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >; _Tp = unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_vector.h:603:31: required from 'constexpr std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::unique_ptr<std::__cxx11::basic_string >; _Alloc = std::allocator<std::unique_ptr<std::__cxx11::basic_string > >]'
main.cpp:42:35: required from here
/usr/include/c++/13/bits/stl_construct.h:96:17: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = std::__cxx11::basic_string; _Dp = std::default_delete<std::__cxx11::basic_string >]'
96 | -> decltype(::new((void*)0) _Tp(std::declval<_Args>()...))
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/13/memory:78,
from task.h:3:
/usr/include/c++/13/bits/unique_ptr.h:522:7: note: declared here
522 | unique_ptr(const unique_ptr&) = delete;
| ^~~~~~~~~~
/usr/include/c++/13/bits/stl_construct.h: In instantiation of 'constexpr void std::_Construct(_Tp*, _Args&& ...) [with _Tp = unique_ptr<__cxx11::basic_string >; _Args = {const unique_ptr<__cxx11::basic_string<char, char_traits, allocator >, default_delete<__cxx11::basic_string<char, char_traits, allocator > > >&}]':
/usr/include/c++/13/bits/stl_uninitialized.h:120:21: required from 'constexpr _ForwardIterator std::__do_uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_uninitialized.h:371:30: required from 'constexpr _ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, allocator<_Tp>&) [with _InputIterator = __gnu_cxx::__normal_iterator<const unique_ptr<__cxx11::basic_string >; _Tp = unique_ptr<__cxx11::basic_string >]'
/usr/include/c++/13/bits/stl_vector.h:603:31: required from 'constexpr std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = std::unique_ptr<std::__cxx11::basic_string >; _Alloc = std::allocator<std::unique_ptr<std::__cxx11::basic_string > >]'
main.cpp:42:35: required from here
/usr/include/c++/13/bits/stl_construct.h:119:7: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = std::__cxx11::basic_string; _Dp = std::default_delete<std::__cxx11::basic_string >]'
119 | ::new((void*)__p) _Tp(std::forward<_Args>(__args)...);
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/c++/13/bits/unique_ptr.h:522:7: note: declared here
522 | unique_ptr(const unique_ptr&) = delete;
| ^~~~~~~~~~
Assistant
Существующие ошибки указывают на попытку копирования объекта std::unique_ptr, что, как мы знаем, явно запрещено в C++. Ошибка "use of deleted function 'std::unique_ptr::unique_ptr(const std::unique_ptr&)'" возникла из-за того, что где-то в коде (в компиляторе на уровне STL) или, возможно, в вашем коде происходит неявное копирование объекта std::unique_ptr.
Давайте проанализируем, где может быть корень проблемы и как его можно исправить.
Потенциальные причины проблемы
Передача по значению:
В возможном месте своего кода вы, вероятно, пытаетесь использовать вектор std::unique_ptr, используя его конструктор копирования или оператор присваивания, что может вызвать подобные ошибки.
Использование const векторов:
Использование const при работе с вектором/векторами уникальных указателей, так как это может вызвать копирование.
Не используется std::move:
При добавлении объектов std::unique_ptr в вектору везется копирование вместо std::move.
Исправление
Убедитесь, что в коде нигде не происходит неявная попытка копирования вектора std::unique_ptr, включая:
Убедитесь, что вы правильно обрабатываете возвращаемые значения и параметры функций с unique_ptr.
Используйте std::move всякий раз, когда вы перемещаете объект unique_ptr в новую позицию или контейнер.
for i in range(100,1,-1):
if (ans(i) == 9):
print(i)
break
Assistant
Ваш код пытается найти число i в диапазоне от 100 до 2, чьё двоичное представление (после инверсии) становится равным 9. Давайте разберём, в чём может быть проблема.
Проблемы в коде:
Конвертация обратно в int:
В строке return int(s), метод int без указания основания предполагает, что строка представляет собой десятичное число, но в s у вас все еще двоичное число после инверсии. Это приводит к тому, что функция возвращает неправильное число.
Проблемы с диапазоном цикла:
Цикл for i in range(100,1,-1): начинает цикл с 100 и заканчивает на 2, что, в зависимости от поведения, может вызвать неполадки в диапазоне проверки.
Исправление кода:
Вы должны передать основание 2 в int() для правильного преобразования двоичной строки в число. Вот как можно исправить код:
python
def ans(x):
# Получаем двоичное представление числа без префикса '0b'
s = bin(x)[2:]
# Переворачиваем строку
s = s[::-1]
# Конвертируем обратно в число, интерпретируя как двоичное
return int(s, 2)
for i in range(100, 1, -1):
if ans(i) == 9:
print(i)
break
Объяснение изменений:
Верное преобразование строки в число:
int(s, 2) интерпретирует строку s как двоичное число и возвращает его десятичное представление.
Теперь код проверяет все числа от 100 до 2 и ищет первое число, у которого двоичное число перевернуто и преобразовано обратно в десятичное, равно 9.
&, const std::unique_ptr<std::__cxx11::basic_string >&)'
539 | std::construct_at(__p, std::forward<_Args>(__args)...);
| ~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/13/bits/stl_iterator.h:85,
from /usr/include/c++/13/bits/stl_algobase.h:67,
from /usr/include/c++/13/vector:62:
/usr/include/c++/13/bits/stl_construct.h:94:5: note: candidate: 'template<class _Tp, class ... _Args> constexpr decltype (::new(void
Ошибка возникает, если где-то в тестовом коде или внутри ваших функций осуществляется попытка копирования объекта типа std::unique_ptr.
Здесь нет явных ошибок в самой логике DeDuplicate и Duplicate:
В коде тестового примера могут быть неочевидные попытки неявного копирования векторов с unique_ptr. Убедитесь, что на всех уровнях программы, включая все использованные заголовочные файлы, конструкторы, операторы, не происходит копирования объектов, содержащих unique_ptr.
Консультации по отладке
Убедитесь в отсутствие копирования векторов с unique_ptr:
Используйте только передачи по ссылке там, где это возможно, и перемещение при необходимости.
Используйте отладочный вывод:
Выводите диагностические сообщения с информацией о статусе и адресах указателей перед и после вызова функций, чтобы убедиться, что корректные данные передаются и выходят из функций.
Проверьте компиляторские опции и предупреждения:
Возможно, ваш компилятор настроен на строгий контроль за использованием временных объектов с unique_ptr, и предупреждения могут интерпретироваться как ошибки.
Проверка использования в тестах:
Убедитесь, что тесты используют Duplicate и DeDuplicate правильно, так как ошибка может возникать из-за неверных данных или ошибок при работе с тестируемыми контейнерами.
Попробуйте выполнить эти проверки и посмотреть на результат. Если ошибки все же продолжают возникать, обратите внимание на компиляторские предупреждения и измените участок кода, где пытается происходить копирование данных.
Убедитесь, что ничего очевидного, что может вызвать фактическую копию уникальных указателей через вызов функции или иные манипуляции с векторами.
Диагностика компилятора:
Запустите компилятор с дополнительными диагностическими опциями, чтобы установить, где возникают проблемы.
Присутствие дополнительных сообщений отмены ошибок может указать точное место возникновения проблем.
Будьте внимательны с изменениями const и возможными копиями векторов в вашем проекте. Если проблема не удастся решить, сообщите, где возникает ошибка в какой строке кода, чтобы сузить область поиска.