C++ C++;,标准::列表的左/右旋转
有没有办法在列表中使用C++ C++;,标准::列表的左/右旋转,c++,algorithm,list,vector,rotation,C++,Algorithm,List,Vector,Rotation,有没有办法在列表中使用std::rotate std::list<int> v = { 0,7, 1,2 }; 为向量工作 std::vector<int> v = { 0, 7, 1, 2 }; std::vector v={0,7,1,2}; 一种可能的方法是将列表复制到向量 std::vector<int> u{ std::begin(v), std::end(v) }; std::vector u{std::begin(v),std::end(
std::rotate
std::list<int> v = { 0,7, 1,2 };
为向量工作
std::vector<int> v = { 0, 7, 1, 2 };
std::vector v={0,7,1,2};
一种可能的方法是将列表复制到向量
std::vector<int> u{ std::begin(v), std::end(v) };
std::vector u{std::begin(v),std::end(v)};
反之亦然,但我觉得它太“冗长”。。。直接旋转列表会导致以下错误:
Error C2672 'std::rotate': no matching overloaded function found
Error C2676 binary '+': std::_List_iterator<std::_List_val<std::_List_simple_types<_Ty>>>' does not define this operator or a conversion to a type acceptable to the predefined operator
错误C2672'std::rotate':未找到匹配的重载函数
错误C2676二进制“+”:std::_List_iterator”未定义此运算符或到预定义运算符可接受的类型的转换
感谢您的帮助。调用的唯一语法问题
std::rotate(v.begin(), v.begin() + 1, v.end());
就是说,std::list
迭代器不建模,但是。因此,不能向它们添加或从中减去整数值。相反,像这样调用std::rotate
std::rotate(v.begin(), std::next(v.begin()), v.end());
std::rotate(v.rbegin(), std::next(v.rbegin()), v.rend());
在这里,
std::next
增加迭代器,不管它满足什么概念。这就是为什么有时最好首先使用它(在您的情况下,当使用std::vector
时),因为它添加了一级间接寻址,而不是someIterator+1
,在那里您硬连接随机访问要求。您不能添加到std::list
迭代器,因为它不是随机访问。但是你可以增加它。这就是std::next
为您所做的:
void rot_slow( std::list<Item>& seq )
{
std::rotate( seq.begin(), next( seq.begin() ), seq.end() );
}
这使用0项交换,O(1)复杂度。您的问题不是轮换,而是迭代器类型<代码>标准::列表has。它们不实现
操作符+
。你必须先迭代到你想要的新点。。。顺便说一句:您只需根据需要实现一个操作符+
重载即可。我不认为这是“唯一的问题”。“到目前为止。”干杯,桑德。-阿尔夫,我明白你的意思了。“Only”是指代码的语法部分。我会澄清的。不知怎的,我期待/希望rotate会对列表迭代器造成过载。。。
void rot_slow( std::list<Item>& seq )
{
std::rotate( seq.begin(), next( seq.begin() ), seq.end() );
}
void rot_fast( std::list<Item>& seq )
{
seq.splice( seq.end(), seq, seq.begin() );
}