私は、リンクされたリスト(以下コード)に追加するには、このヘルパーメソッドを持っています。のstd ::のstd ::ベクトル対initializer_list問題:未定義bahevior
void append(const std::initializer_list<T>& vals) {
for (const auto& val : vals)
append(val);
}
私が最初1,5,7-を追加しようとしました、 9 std :: vector with this:
void append(const std::vector<T>& vals) {
for (const auto& val : vals)
append(val);
}
ただし、1,5,7,9ではなく0,0,7,9で埋められています。なぜどんなアイデア?ここで
は、全体のコードです:ここ
template <typename T>
class LinkedList {
private:
struct Node {
const T& val_;
std::shared_ptr<Node> next_ = nullptr;
Node(const T& val) : val_(val) {}
};
public:
std::shared_ptr<Node> head_ = nullptr;
std::shared_ptr<Node> current = nullptr;
// could be optimized
void append(const std::initializer_list<T>& vals) {
for (const auto& val : vals)
append(val);
}
void append(const T& val) {
if (!head_) {
head_ = std::make_shared<Node>(val);
return;
}
current = head_;
while (current->next_)
current = current->next_;
current->next_ = std::make_shared<Node>(val);
}
template <typename Func>
void for_each(Func f) {
current = head_;
while (current) {
f(current->val_);
current = current->next_;
}
}
};
int main() {
LinkedList<int> lst;
lst.append({1,5,7,9});
auto printer = [](int val) {
std::cout << val << " ";
};
lst.for_each(printer);
std::cout << '\n';
}
あなたは何をしているのかを確認するためにコードをステップしましたか? – NathanOliver
なぜ右後行スペーシングの任意の量がありますか? –
ノードは、どちらの場合もダングリングリファレンスを格納します。 –