小编Arn*_*rne的帖子

Initializing variables in an "if" statement

I read that in C++17 we can initialize variables in if statements like this

if (int length = 2; length == 2)
    //execute something
Run Code Online (Sandbox Code Playgroud)

Instead of

int length = 2;
if (length == 2)
    //do something
Run Code Online (Sandbox Code Playgroud)

Even though it is shorter, it affects the code readability (especially for people who don't know this new feature), which I suppose is a bad coding practice for large software development.

除了使代码更短之外,使用此功能还有什么好处?

c++ c++17

78
推荐指数
6
解决办法
4834
查看次数

从对向量中按值擦除元素

C ++ 20开始,我们可以通过执行以下操作从向量中按值删除元素:

std::vector<int> v = {10,20,30,40,50};
std::erase(v,30);
Run Code Online (Sandbox Code Playgroud)

那真的很方便,更不用说了std::erase_if

但是,如果我们有一个成对的向量并且要擦除,仅当成对的second值匹配时该怎么办?

std::pair<int, std::string> foo = std::make_pair(1,"1");
std::pair<int, std::string> foo2 = std::make_pair(2,"2");

std::vector< std::pair<int, std::string> > v;
v.push_back(foo);
v.push_back(foo2);

std::erase(v, make_pair(1,"2"));    //This is not going to work!
Run Code Online (Sandbox Code Playgroud)

那么,有没有一种方法可以通过second向量对中的值擦除元素?

c++ vector c++20

6
推荐指数
1
解决办法
93
查看次数

指针是否需要指向分配的类数组中的第一个对象才能使用“ delete [] ptrName”?

目前,我正在编写一些代码,以练习我在在线教程中研究的内容。在这段代码中,我使用指针使用“ new”分配了一些空间来创建类实例,并遍历它们以设置其名称。但是,我只能在指针位于第0位时删除它们。有人可以解释一下我是否对此想法有误,或者对此的一般规则是什么?

//头文件

#include <iostream>
using namespace std;

class Animal {
private:
    string name;
    int age;

public:
    Animal(string name = "UNDEFINED", int age = 0): name(name), age(age) {cout << "Animal created" << endl;}
    ~Animal() {cout << "Animal killed" << endl;}
    void setName(char name) {this->name = name;}
    void speak() {cout << "My name is: " << name << ", and my age is: " << age << endl;}

};
Run Code Online (Sandbox Code Playgroud)

//主文件

#include "Animal.h"

int main() {
    char name = 'a';

    Animal *animals …
Run Code Online (Sandbox Code Playgroud)

c++

0
推荐指数
1
解决办法
65
查看次数

标签 统计

c++ ×3

c++17 ×1

c++20 ×1

vector ×1