我正在使用范围库来帮助我的类中的文件管理器数据,如下所示:
class MyClass
{
public:
MyClass(std::vector<int> v) : vec(v) {}
std::vector<int> getEvens() const
{
auto evens = vec | ranges::views::filter([](int i) { return ! (i % 2); });
return std::vector<int>(evens.begin(), evens.end());
}
private:
std::vector<int> vec;
};
Run Code Online (Sandbox Code Playgroud)
在这种情况下,函数中构造了一个新向量getEvents()。为了节省这种开销,我想知道是否可以/建议直接从函数返回范围?
class MyClass
{
public:
using RangeReturnType = ???;
MyClass(std::vector<int> v) : vec(v) {}
RangeReturnType getEvens() const
{
auto evens = vec | ranges::views::filter([](int i) { return ! (i % 2); });
// ...
return evens;
}
private:
std::vector<int> vec;
};
Run Code Online (Sandbox Code Playgroud)
如果可能的话,我是否需要考虑任何终生注意事项? …
我有我已经实现为一个二维阵列std::vector的std::vectorS,如下所示:
struct Cell
{};
struct Column
{ std::vector<Cell*> m_column; };
struct Grid
{ std::vector<Column> m_grid; }
Run Code Online (Sandbox Code Playgroud)
我想为Grid构建一个输入迭代器类,以便您可以执行此操作...
for (const auto cell : grid)
cell->doSomething();
Run Code Online (Sandbox Code Playgroud)
...并使用其他STL算法。但是我不确定如何使迭代器递增功能。
这是我到目前为止的内容:
struct Grid
{
std::vector<Column> m_grid;
struct ConstIterator
{
using value_type = const Cell*;
using reference = const Cell*&;
using pointer = const Cell**;
using difference_type = std::ptrdiff_t;
using iterator_category = std::input_iterator_tag;
reference operator* () { return curr; }
ConstIterator& operator++ () { incrementAcrossGrid(); return *this; }
ConstIterator operator++(int) { const …Run Code Online (Sandbox Code Playgroud) 我已经学会了重载operator<以使自定义类与 STL 算法兼容,就像这样:
struct A
{ int a; };
bool operator< (const A& x, const A& y)
{ return x.a < y.a; }
std::vector<A> aOne, aTwo, aResult;
std::set_difference(aOne.begin(), aOne.end(),
aTwo.begin(), aTwo.end(),
std::inserter(aResult, aResult.begin()));
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用JUCE 库中的ValueTree对象做同样的事情时,它失败了:
bool operator< (const juce::ValueTree& x, const juce::ValueTree& y)
{
// let's now worry about the implementation of this function here...
return true;
}
std::vector<juce::ValueTree> vOne, vTwo, vResult;
std::set_difference(vOne.begin(), vOne.end(),
vTwo.begin(), vTwo.end(),
std::inserter(vResult, vResult.begin()));
// COMPILER ERROR: Failed to specialize function template …Run Code Online (Sandbox Code Playgroud) 我想在一个将在std :: vector中实例化的类上定义一个移动构造函数.但是,移动构造函数似乎会干扰向量的初始化.
#include <iostream>
#include <vector>
class cell
{
private:
int m_value;
public:
void clear() {m_value = 0;}
cell(int i = 0): m_value(i) {}
cell(const cell&& move): m_value(move.m_value) {} //move constructor
cell& operator= (const cell& copy)
{
if (© == this) return *this;
clear();
m_value = copy.m_value;
return *this;
}
int getValue() const {return m_value;}
};
int main()
{
cell mycell {3}; // initializes correctly
std::vector<cell> myVec {1, 2, 3, 4}; // compile error.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我已经做了很多研究,但还没有找到解决这个问题的方法.C++编程的新手.
编辑:我的类最终会有更多的m_value,包括一些非基本类型,因此我不想使用默认的复制构造函数.