当我创建一个std :: vector对象时,并不总是调用这些对象的构造函数.
#include <iostream>
#include <vector>
using namespace std;
struct C {
int id;
static int n;
C() { id = n++; } // not called
// C() { id = 3; } // ok, called
};
int C::n = 0;
int main()
{
vector<C> vc;
vc.resize(10);
cout << "C::n = " << C::n << endl;
for(int i = 0; i < vc.size(); ++i)
cout << i << ": " << vc[i].id << endl;
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的输出:
C::n = 1 …Run Code Online (Sandbox Code Playgroud) 我知道手动动态内存分配通常是一个坏主意,但它有时比使用更好的解决方案,比方说,std::vector?
举一个粗略的例子,如果我必须存储一个n整数数组,其中n<= 16,比如说.我可以使用它来实现它
int* data = new int[n]; //assuming n is set beforehand
Run Code Online (Sandbox Code Playgroud)
或使用矢量:
std::vector<int> data;
Run Code Online (Sandbox Code Playgroud)
使用一个std::vector或者是否存在实际情况,手动分配动态内存是一个更好的想法,以提高效率,这绝对是一个更好的主意吗?
我使用下面的代码找到一个字符串std::vector的string类型.但是如何返回特定元素的位置?
码:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<string> vec;
vector<string>::iterator it;
vec.push_back("H");
vec.push_back("i");
vec.push_back("g");
vec.push_back("h");
vec.push_back("l");
vec.push_back("a");
vec.push_back("n");
vec.push_back("d");
vec.push_back("e");
vec.push_back("r");
it=find(vec.begin(),vec.end(),"r");
//it++;
if(it!=vec.end()){
cout<<"FOUND AT : "<<*it<<endl;
}
else{
cout<<"NOT FOUND"<<endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
FOUND AT : r
预期产出:
FOUND AT : 9
我正在尝试为我的软件定义一个好的设计,这意味着要小心对某些变量的读/写访问.在这里,我简化了讨论的程序.希望这对其他人也有帮助.:-)
假设我们有一个类X如下:
class X {
int x;
public:
X(int y) : x(y) { }
void print() const { std::cout << "X::" << x << std::endl; }
void foo() { ++x; }
};
Run Code Online (Sandbox Code Playgroud)
我们还要说,将来这个类将被子类化为X1,X2,......这可以重新实现print()和foo().(virtual为了简单起见,我省略了所需的关键字,因为它不是我面临的实际问题.)
既然我们将使用polymorphisme,那么让我们使用(智能)指针并定义一个简单的工厂:
using XPtr = std::shared_ptr<X>;
using ConstXPtr = std::shared_ptr<X const>;
XPtr createX(int x) { return std::make_shared<X>(x); }
Run Code Online (Sandbox Code Playgroud)
到目前为止,一切都很好:我可以定义goo(p)哪些可以读写p,hoo(p)哪些只能读取p.
void goo(XPtr p) {
p->print();
p->foo();
p->print();
}
void hoo(ConstXPtr p) {
p->print();
// p->foo(); …Run Code Online (Sandbox Code Playgroud) 我有一个可复制构造的结构向量,但不可赋值:
struct Struct
{
inline Struct(const std::string& text, int n) : _text(text), _n(n) {}
inline Struct(const Struct& other) : _text(other._text), _n(other._n) {}
const std::string _text;
const int _n;
Struct& operator=(const Struct&) = delete;
};
Run Code Online (Sandbox Code Playgroud)
一切都很好.事实上,我甚std::vector<Struct>至可以将值作为函数的返回值传递.然而,这失败了:
std::vector<TextFragment> v1, v2;
v2 = v1;
Run Code Online (Sandbox Code Playgroud)
当然,错误是:
错误:C2280:'Struct&Struct :: operator =(const Struct&)':尝试引用已删除的函数
我不明白为什么它试图调用它.这是否是某种优化以避免重新分配向量的内存块?
在使用的类的主动开发期间std::vector,通常会发生索引超出范围.(有关实际示例,请参阅此代码复习问题.)使用时operator[],会导致未定义的行为.尽管如此,[]语法易于阅读比写作更方便.at().
因此,我想使用[]运算符编写代码,但同时启用了边界检查.在测试代码之后,应该很容易删除边界检查.
我在考虑以下代码:
util::bound_checked<std::vector<int>> numbers;
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(3);
numbers.push_back(4);
std::cout << numbers[17] << "\n";
Run Code Online (Sandbox Code Playgroud)
对我来说,这个实用程序模板似乎是如此简单,我希望它存在.可以?如果是这样,以哪个名字?
下面的代码片段演示了我最近在程序中遇到的一个实际问题:
#include<vector>
class A;
void f( const std::vector<A> & = {} );
Run Code Online (Sandbox Code Playgroud)
有一个不完整的类A和一个带有空默认值的vector函数声明。A而且该函数甚至没有在任何地方被调用。
它在 GCC 和 Clang 14 中工作正常,但从 Clang 15 开始出现错误:
In file included from <source>:1:
/opt/compiler-explorer/clang-15.0.0/bin/../include/c++/v1/vector:540:52: error: arithmetic on a pointer to an incomplete type 'A'
{return static_cast<size_type>(__end_cap() - this->__begin_);}
~~~~~~~~~~~ ^
/opt/compiler-explorer/clang-15.0.0/bin/../include/c++/v1/vector:760:56: note: in instantiation of member function 'std::vector<A>::capacity' requested here
__annotate_contiguous_container(data(), data() + capacity(),
^
/opt/compiler-explorer/clang-15.0.0/bin/../include/c++/v1/vector:431:7: note: in instantiation of member function 'std::vector<A>::__annotate_delete' requested here
__annotate_delete();
^
<source>:5:32: note: in …Run Code Online (Sandbox Code Playgroud) c++ forward-declaration stdvector language-lawyer incomplete-type
我是C++的新手,我正在尝试制作一个小地牢爬虫游戏.目前我在头文件中声明了多个向量,但它们似乎给出了多个错误.我试过在StackOverflow上搜索这个问题,但答案似乎并没有起作用.
这是我的一个头文件:(Hero.h)
#pragma once
class Hero {
public:
Hero();
std::string name;
int experience;
int neededExperience;
int health;
int strength;
int level;
int speed;
std::vector<Item> items = std::vector<Item>();
void levelUp();
private:
};
Run Code Online (Sandbox Code Playgroud)
这是我的.cpp文件:(Hero.cpp)
#include "stdafx.h"
#include <vector>
#include "Hero.h"
#include "Item.h"
Hero::Hero() {
}
void Hero::levelUp()
{
};
Run Code Online (Sandbox Code Playgroud)
就像我说我是C++的新手,所以我的代码可能比我知道的更多错.这只是一个考验.
以下是Visual Studio 2015的错误列表中显示的错误:
Error C2039 'vector': is not a member of 'std' CPPAssessment hero.h 13
Error C2143 syntax error: missing ';' before '<' CPPAssessment hero.h 13
Error C4430 missing type specifier - …Run Code Online (Sandbox Code Playgroud) 考虑以下代码:
#include <vector>
#define BROKEN
class Var {
public:
#ifdef BROKEN
template <typename T>
Var(T x) : value(x) {}
#else
Var(int x) : value(x) {}
#endif
int value;
};
class Class {
public:
Class(std::vector<Var> arg) : v{arg} {}
std::vector<Var> v;
};
Run Code Online (Sandbox Code Playgroud)
不管是否BROKEN定义,Clang ++(7.0.1)都会编译此错误,而如果BROKEN已定义,则g ++(8.2.1)会引发错误:
main.cpp:9:20: error: cannot convert ‘std::vector<Var>’ to ‘int’ in initialization
Var(T x) : value(x) {}
^
Run Code Online (Sandbox Code Playgroud)
据我所知,std::vector(std::vector&&)在两种情况下,这里使用的统一初始化都应选择构造函数。但是,显然,g++它将{arg}视为初始化列表,并尝试初始化应用于向量的vwith 的第一个元素Var,这将不起作用。
如果BROKEN未定义,则g ++显然足够聪明,可以意识到initializer_list重载将无法正常工作。
哪个是正确的行为,或者标准都允许? …
我注意到std::ranges::sort无法排序std::vector<bool>:
<source>:6:51: error: no match for call to '(const std::ranges::__sort_fn) (std::vector<bool, std::allocator<bool> >)'
6 | std::ranges::sort(std::vector{false, true, true});
|
Run Code Online (Sandbox Code Playgroud)
这是允许的吗?我们是否需要专门化std::ranges::sortfor std::vector<bool>?是否有关于委员会如何考虑这一点的任何信息?
c++ ×10
stdvector ×10
c++11 ×3
stl ×2
c++20 ×1
const ×1
constructor ×1
iterator ×1
shared-ptr ×1
static ×1
std-ranges ×1
vector ×1