是否可以对迭代器定义的列表(列表的子集)的部分进行排序std::sort?
即,std::list唯一可用的排序是通过一种方法(http://en.cppreference.com/w/cpp/container/list/sort),我希望能够使用它的迭代器对列表的一部分进行排序std::sort.例如
std::sort(listItrStart, listItrEnd, [](T& a, T& b){ return a.something() < b.something()});
Run Code Online (Sandbox Code Playgroud)
我感谢一旦对项目执行了移动操作,迭代器将变为无效,我认为这意味着在下一次"比较"之前,迭代器无法对列表进行排序而无需重新迭代到所需位置?
在这种情况下,排序子列表的最佳做法是什么,而不为此过程填充另一个容器(如果有的话)?
非常感谢.
我有一个问题,即在使用 VS2017(C++14、C++17 和 ISO 最新版本)时,我无法将某个构造函数与数组初始值设定项一起使用。
当它应该使用填充有单个元素的容器调用构造函数时,我收到C2397 conversion from 'double' to 'unsigned int' requires a narrowing conversion错误。
#include <vector>
class obj
{
public:
obj(const std::vector<double>& values, unsigned int stride)
: values_(values), stride_(stride)
{
}
obj(unsigned int m, unsigned int n)
: stride_(n)
{
}
private:
unsigned int stride_;
std::vector<double> values_;
};
int main(int argc, char** argv)
{
obj m(1, 1); // correct constructor called.
obj mm({ 42.0 }, 1); // Error C2397
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我可以通过显式声明容器来解决这个问题......
obj mm(std::vector<double>({ 42.0 …Run Code Online (Sandbox Code Playgroud) 在计算两个向量之间的角度时,我传统上使用 acos,但这需要对两个向量进行归一化。atan2 可用于完成相同的(特别是atan2(b.y_, b.x_) - atan2(a.y_, a.x_)),这是否需要归一化向量?
如果 atan2 不需要归一化向量,这是否更好用,因为归一化可能成本高昂且“更多”容易出错,因为它需要 sqrt 操作?
然后我读到 atan2 本身可能比 acos 更昂贵,但更准确?然后我还阅读了其他建议相反的互联网:( 很多相互矛盾的信息,不确定使用 acos 或 atan 计算两个向量之间的角度有什么关系。
推荐哪个?以及每次使用的好处/问题是什么?
任何帮助将不胜感激,谢谢!
考虑这个shared_ptr<T>以各种方式构造并返回的示例:
#include <memory>
#include <iostream>
class Base
{
public:
virtual ~Base() {}
Base(int y) : y_(y) {}
int y_;
};
class Derived : public Base
{
public:
Derived(int y, int z) : Base(y), z_(z) {}
int z_;
};
std::shared_ptr<Base> A()
{
return std::shared_ptr<Base>(new Derived(1, 2));
}
std::shared_ptr<Base> B()
{
std::shared_ptr<Derived> result = std::make_shared<Derived>(Derived(1, 2));
return result;
}
std::shared_ptr<Base> C()
{
std::shared_ptr<Base> result = std::make_shared<Base>(Derived(1, 2));
return result;
}
std::shared_ptr<Base> D()
{
return std::make_shared<Base>(Derived(1, 2));
}
int main(int argc, …Run Code Online (Sandbox Code Playgroud) c++ ×4
angle ×1
atan ×1
c++17 ×1
iterator ×1
list ×1
make-shared ×1
shared-ptr ×1
sorting ×1
trigonometry ×1
vector-space ×1