我有一个独特的指针向量.其中,我想要一个不占用其尖头物体的所有权.怎么做?
vector<unique_ptr<int>> v;
v.push_back(make_unique<int>(10));
unique_ptr<int> p(new int(20)); // add it to v but keep p take the ownership.
Run Code Online (Sandbox Code Playgroud)
问题来自以下案例.我有一个树结构的数据,由GUI树小部件表示.父节点通过使用来获取其子节点的所有权vector<unique_ptr<T>>.但有一个例外.我有一个常见的单例数据,并希望将它附加到树上,以便友好的用户界面.有冲突因为sigleton也取得了所有权.使用share_ptr有效,但牺牲了一些性能.
感谢所有人的回答,评论和建议.这可能是一个设计缺陷.也许我需要一个特殊父节点的新类vector<unique_ptr<T>>(对于其他人)和shared_ptr甚至一个原始指针(对于单例)来处理异常.
如何获取整数参数包中的第i个整数?例如
template<int... Is>
struct A
{
enum { CONSTANT_0 = Is[0] }; //Assume the sizeof...(Is) > the index requested
};
Run Code Online (Sandbox Code Playgroud) 例如
class A
{
int m_x;
float m_y;
double m_z;
int x() const {return m_x;}
float y() const {return m_y;}
double z() const {return m_z;}
};
Run Code Online (Sandbox Code Playgroud)
变得像
class A
{
MY_MACRO((int)(float)(double), (x)(y)(z));
};
Run Code Online (Sandbox Code Playgroud)
请使用boost预处理器序列来执行此操作,因为此宏将与已使用boost预处理器序列的其他现有宏组合.
例如,我有一个班级
struct A
{
A(int i, double d) {...}
};
Run Code Online (Sandbox Code Playgroud)
和带参数A的函数
void f(A a);
Run Code Online (Sandbox Code Playgroud)
我可以通过调用函数
f( { 1, 3.14 } );
Run Code Online (Sandbox Code Playgroud)
如果函数有参数A*
void g(A* a);
Run Code Online (Sandbox Code Playgroud)
怎么叫它像
g( my_new{1, 3.14} ); // Note: no type A is shown here.
Run Code Online (Sandbox Code Playgroud)
或者如何在这里推导出类型A?
例如
template<typename T> void f(T&& t) {}
template<typename T> void f(T const& t) {}
Run Code Online (Sandbox Code Playgroud)
我打电话的时候
int i;
f(i); // call f(T&&) which I expect to call f(T const&), how to solve it?
f(10); // call f(T&&), that is fine
Run Code Online (Sandbox Code Playgroud) (T)value和之间有T(value)什么区别?例如(float)3.14和float(3.14).哪个更快或更好?
由于精度有限,浮点数并不准确。我的问题是:在浮点数计算机计算中,乘法是可交换的吗?
例如
double a = ..;
double b = ...;
double c = a * b;
double d = b * a;
if (c == d)
cout << "Yes, great floating";
Run Code Online (Sandbox Code Playgroud) 如果我使用intindex来访问vector元素,它会将整数转换为size_t,然后调用operator[](size_t)函数吗?是否有任何性能下降?
例如
class School
{
public List<Student> Students {get; private set;}
}
Run Code Online (Sandbox Code Playgroud)
这School不是不可变的,因为getter Students是一个可变的集合.如何使类不可变?
我认为 ImmutableList 在添加和删除元素方面比 List 慢得多。那正确吗?
基准测试。添加的 ImmutableList 和 RemoveAt 的性能很好。RemoveAt 甚至比 List 更快。
static void Main(string[] args)
{
// Generic List Test
var genericList = new List<int>();
var sw = Stopwatch.StartNew();
for (int i = 0; i < 20000; i++)
{
genericList.Add(i);
}
sw.Stop();
Console.WriteLine("Add duration for List<T>: " + sw.ElapsedMilliseconds);
IList<int> completeList = new List<int>(genericList);
sw.Restart();
// Remove from 20000 -> 0.
for (int i = completeList.Count - 1; i >= 0; i--)
{
genericList.RemoveAt(0);
}
sw.Stop();
Console.WriteLine("Remove duration …Run Code Online (Sandbox Code Playgroud)