Использование <algorithm>
и C ++ 11:
#include <algorithm>
#include <vector>
// personally, I would pass "in" as a couple of iterators
template<typename T>
std::vector<std::vector<T>> list_one_removed(const std::vector<T>& in)
{
std::vector<std::vector<T>> result;
for (auto itor = in.begin(); itor != in.end(); ++itor) {
std::vector<T> buffer;
std::copy_if(in.begin(),
in.end(),
std::back_inserter(buffer),
[&itor](const T& t){ return &t != &(*itor); });
result.emplace_back(std::move(buffer));
}
return result;
}
Если у вас есть новый цикл «для каждого», вы можете сделать:
#include <algorithm>
#include <vector>
template<typename T>
std::vector<std::vector<T>> list_one_removed(const std::vector<T>& in)
{
std::vector<std::vector<T>> result;
for (const auto& foo : in) {
std::vector<T> buffer;
std::copy_if(in.begin(),
in.end(),
std::back_inserter(buffer),
[&foo](const T& t){ return &t != &foo; });
result.emplace_back(std::move(buffer));
}
return result;
}
Если вы используете C ++ 03:
#include <algorithm>
#include <vector>
template<typename T> struct identity {
const T& id_;
identity(const T& id) : id_(id) { }
bool operator()(const T& other) const
{
return &id_ == &other;
}
};
template<typename T>
std::vector<std::vector<T> > list_one_removed(const std::vector<T>& in)
{
std::vector<std::vector<T> > result;
for (typename std::vector<T>::const_iterator itor = in.begin();
itor != in.end();
++itor) {
std::vector<T> buffer;
std::remove_copy_if(in.begin(),
in.end(),
std::back_inserter(buffer),
identity<T>(*itor));
result.push_back(buffer);
}
return result;
}