标签: stdvector

当将 std::vector::begin() 传递给 std::vector::insert 时,编译器如何推断出要调用哪个版本的 std::vector::begin() ?

我正在尝试制作自己的迷你向量类,并且正在尝试复制一些函数,但是在传递诸如begin()和end()作为参数之类的调用时,我无法让它们以相同的方式运行 - 编译器不会推断出正确的版本。这是一个例子:

template<typename T>
class Iterator
{
public:
Iterator() {}
};

template<typename T>
class ConstIterator
{
public:
ConstIterator() {}
};

template <typename T>
class MyList {
   public:
    MyList() {}

    Iterator<T> Begin()
    {
        return Iterator<T>();
    }

    ConstIterator<T> Begin() const
    {
        return Iterator<T>();
    }

    void Insert(ConstIterator<T> it) 
    {

    }
};


int main() {
    MyList<int> myList;

    myList.Insert(myList.Begin());
}
Run Code Online (Sandbox Code Playgroud)

它myList.Insert(myList.Begin());不会尝试使用Begin()const 的正确版本。

据我在 std::vector 实现中所知,有两个版本的 begin() - 一个返回 an iterator,一个返回 a const_iterator。它们之间唯一的区别是一个是 const 方法(返回 …

c++ containers templates stl stdvector

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

将向量变量分配给自身是否会导致复制 C++

假设我有一个向量:

std::vector<uint64_t> foo;
foo.push_back(1);
foo.push_back(27);
Run Code Online (Sandbox Code Playgroud)

我通过引用将该向量传递给函数。

calculate_something(foo);

int calculate_something(std::vector<uint64_t>& vec) {
  // ...
}
Run Code Online (Sandbox Code Playgroud)

在极少数情况下,函数需要本地修改向量,在这种情况下必须创建副本。这是正确的方法吗?

if (some_condition) {
  vec = vec;
}

vec.push_back(7);
Run Code Online (Sandbox Code Playgroud)

编辑:我自我分配的原因是因为分配给另一个变量会产生一个副本,我的直觉告诉我,当分配回同一个变量时,也会发生同样的情况。

c++ copy stdvector

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

STD 包装器围绕 std::vector 的一部分(或替代方案)

我目前使用 std::vector 来存储一些数据(注意:大小在构造时已知,之后不会更改:如果您看到比向量更好的结构,这对我来说很好)。稍后在程序中,我需要将部分数据(前 N 个值)传递给优化函数,该函数将就地修改它。

一个简单的解决方案是传递对整个向量的引用以及用于优化的部分的索引。但是,如果我可以避免告诉优化函数(及其子函数)要优化哪一部分,而只给它们一个仅包含要优化的值的向量/数组/you_name_it,那就太好了。

所以基本上,我想要两个“数组”之类的对象(都是恒定大小,但大小仅在运行时知道)共享相同的内存。

例如,如果 std::vector 的成员是公共的,一个简单的解决方案是

std::vector<int> original_vector={0,1,2,3,4,5,6,7,8}
std::vector<int> sub_vector(0);
sub_vector.data=original_vector->data; //point to the same data (nb : there is no public data member, just a data() getter, and as far as I know no setter)
sub_vector.length=3;
//sub_vector now appears to contain {0,1,2}
sub_vector[1]=42;
//oringinal_vector now contains {0,42,2,3,4,5,6,7,8}
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是获取数据指针,然后将原始 C 风格指针 + 长度传递给优化函数。但在 C++ 中为数组提供 C 指针并不好。如果有一个 std 容器可以通过 C 指针 + 长度初始化(无需复制),这可能是一个很好的解决方案。

还有其他想法吗?

注意:我还没有编写优化代码,所以如果更容易的话,我也可以将所有要优化的数据放在最后而不是开头。

注意:如果有一种不复制数据的方法,也可以先创建 2 个“子数组”(固定数据和要优化的数据),然后创建全局数组

编辑:目前,我仅限于 C++17,因为 ROS2 还不支持 C+20

c++ arrays pointers stdvector

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

std::vector - 为什么调用删除后元素仍然存在?

我有这段代码,我不明白为什么我需要delete然后pop_back()。
我可以只做1次手术吗?

struct T
 {
    T(int n):x(n){};
    int print() {
       return x; 
    };
    private:
        int x;
 };

int main(int argv,char** argc)
{
    std::vector t = { new T(1),new T(2)};
    delete t.back();
    std::cout << t.size() << std::endl;
    std::cout << t.back()->print() << std::endl;

    t.pop_back();
    std::cout << t.size() << std::endl;
    std::cout << t.back()->print() << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出 - 正如您所看到的,delete向量看起来仍然保留着没有对象的元素:

2
179185600
1
1 
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么我需要delete然后删除,不能在单个命令中完成相同的操作吗?

c++ stdvector c++17

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

如何在 std::vector&lt;std::map&lt;int, std::unique_ptr&lt;int&gt;&gt;&gt; 容器中插入元素?

我有std::vector<std::map<int, std::unique_ptr<int>>>容器(如果为了简化)。最初,我必须插入std::vector一定数量的std::map,每个都有一个键值对。我尝试过这样的代码:

#include <iostream>
#include <map>
#include <vector>
#include <memory>

using namespace std;

int main()
{
    vector<map<int, std::unique_ptr<int>>> data{};

    for (int x = 0; x < 10; x++)
    {
        data.emplace_back(std::make_pair(x, std::make_unique<int>(x)));
    }
}
Run Code Online (Sandbox Code Playgroud)

但这没有用。我怎样才能改变它以使其按预期工作?

编辑:我明白我的错误,我必须使用这段代码来添加元素:

std::map<int, std::unique_ptr<int>> m;
m.emplace(x, std::make_unique<int>(y));
data.emplace_back(std::move(m));
Run Code Online (Sandbox Code Playgroud)

然后,该代码可以在在线编译器中运行,但在 Visual Studio 中仍然无法运行。

c++ stdmap stdvector

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

使用 SFML 的 C++ 中基于迭代器的循环和基于索引的循环之间存在显着的性能差异

我正在使用 C++ 中的 SFML 开发一个简单的 2D 网格可视化游戏引擎。我有一个带有 std::vector<sf::Vertex> 的 Grid 类,其中网格中的每个单元格由 6 个顶点表示。当我根据每个单元格的状态更新其颜色时,我观察到两个循环之间存在巨大的性能差异:一个循环使用向量的迭代器,另一个循环使用基于索引的方法。

这是差异所在:

inline void ChangeCellColor(Cell& cell, sf::Color color)
{
    // index-based loop
    auto index = cell.grid_y * width_ + cell.grid_x;
    for (int i = 0; i < 6; ++i)
    {
        vertices_[index * 6 + i].color = color;
    }

    // iterator-based loop (commented out for now)
    /*
    auto index = cell.grid_y * width_ + cell.grid_x;
    for (auto it = vertices_.begin() + index * 6; it != vertices_.begin() + index …
Run Code Online (Sandbox Code Playgroud)

c++ stdvector sfml c++17

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

迭代一个非常非常长的 std::vector 问题

我有一个std::vector<std::tuple<int, int>>能够容纳很多潜在元素的东西。

我事先不知道它会有多少个元素。这取决于我如何运行代码(使用什么输入参数)。

我想迭代这个向量。

目前,我正在做:

for (long long int idx = 0; idx <= (vec.size() - 1); idx++) {
    do_something(vec[idx]);
}
Run Code Online (Sandbox Code Playgroud)

这会产生警告: warning: comparison of integer expressions of different signedness: 'long long int' and 'std::vector<std::tuple<int, int> >::size_type' {aka 'long unsigned int'} [-Wsign-compare]

从SO中,我知道vec.size()返回 a std::vector<std::tuple<int, int> >::size_type,我知道它可能与以下内容不同size_t:/sf/answers/1996006421/

我的问题是:我该如何编写 for 循环来迭代向量的所有元素,而不发出警告?

例如, anint是不够的,我确信向量将容纳多个65535元素。

另外,long unsigned int编译器告诉我.size()返回的内容可能不足以容纳我的向量的所有元素:来自https://en.cppreference.com/w/cpp/language/types,它似乎可以上升至4,294,967,295仅。

根据谷歌的说法,4 294 967 295 …

c++ for-loop stdvector

1
推荐指数
3
解决办法
145
查看次数

std :: vector在代码拆分后无法引用要推入的对象

编辑:在我的代码版本中,aList被引用为指针,但在我当前的版本中仍然存在同样的问题.

在尝试将其拆分为接口文件和实现文件之前,我已完全使用此代码.但是当我拆分它时,编译器告诉我我用不正确的参数调用push_back().所以我理解它不能引用我推动它的对象的类型,虽然它是相同的(afaik,当然:D).

#ifndef _MYHEADER_HPP_
#define _MYHEADER_HPP_
class A{
public:
    std::string someString;
};

class B{
public:
    std::vector<A> aList;
public:
    void addA();
};

#endif /* _MYHEADER_HPP_ */

//implementation file

#include <string>
#include <vector>
#include "myheader.hpp"

void B::addA(){
    A a;
    a.someString = "Hola";
    // Here compiler says : Invalid arguments 'Candidates are: void push_back(const A &)' line 18 Semantic Error
    aList.push_back(a);
}
Run Code Online (Sandbox Code Playgroud)

AFAIK,std :: vector总是执行要推送的对象的副本,并且该副本存储到向量中,所以我认为这不是"a"被分配的问题,我是对的吗?

我做错了什么?谢谢.

c++ std stdvector

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

使用其元素对矢量进行排序

我需要知道如何使用其元素对用户定义类的向量进行排序.假设我有一个名为"coordinates"的类,其中getX和getY方法返回一个int值.我创建了矢量数组'vector PointTwoD vcP2D(5);"

 class coordinates {
 int getX();
 int getY();

  )
Run Code Online (Sandbox Code Playgroud)

现在问题,1)我需要使用getX()对矢量"vcP2D"进行排序,并按asc顺序排序2)假设用户输入"2"作为x坐标.使用该信息我需要找到哪个向量包含2

请指教

c++ vector stdvector c++11

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

在为vector <string>保留较大容量后发生Segfault

我试图从字典文件中读取单词,我在第4行读取文件中的段错误.从我所读到的关于c ++中的向量来使用insert命令我需要指定一个迭代器来用作占位符.要做到这一点,我在我的向量的开头实例化一个迭代器.

 vector<string>::iterator it = dictionaryFile.begin();
Run Code Online (Sandbox Code Playgroud)

在我的for循环中,我使用increment运算符增加迭代器指向的位置

it++;
Run Code Online (Sandbox Code Playgroud)

我基于www.cplusplus.com上的示例.迭代器适用于前3行,然后发生段错误.我仔细检查了我的文件,以确保没有错误的字符被getline读入.我相信这个错误与我做的保留调用有关,以确保矢量没有溢出.

由于我在声明时没有使用关键字new,因此向量限制为5的容量?我找不到任何使用新关键字的例子!

我已经包含导致此错误的代码段.请注意我已经多次重新设计了这个以试图解决这个段错误,这不是我原来的实现.我很感激c ++大师可能有的任何见解.感谢您的时间.

vector<string> dictionaryFile (5, "");                                                                     //Declaration of vector that will hold the words in the dictionary

ifstream input;                                                                                                  //Declaration of input file stream
input.open(inst.c_str());

/********************** Test to see if file was opened ********************************/                
if(!input){
    cerr << "The file " << inst <<" does not exists in this directory" << '\n';
}
/********************** File is successfully opened**********************************/

string temporaryProcessingString = "";                                                                //This string will temporarily hold values read …
Run Code Online (Sandbox Code Playgroud)

c++ vector segmentation-fault stdvector

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