【问题标题】:In C++, How do I store values into a vector that is inside of a vector when the two vectors are of different types?在 C++ 中,当两个向量的类型不同时,如何将值存储到向量内部的向量中?
【发布时间】:2017-01-31 03:57:19
【问题描述】:

我正在编写一个程序,我需要使用以下数据结构:

struct shape
{  
    std::vector<float> verts; // contains the x & y values for each vertex   
    char type;                // the type of shape being stored.   
    float shapeCol[3];        // stores the color of the shape being stored.   
    float shapeSize;          // stores the size of the shape if it is a line or point
};

在我的主程序中,我需要一个shape 类型的向量。如何使用结构形状的向量将值存储到结构形状内部的向量中。

例如,vector&lt;shape&gt; myshapes

如果我想将一个值存储到我的verts 向量的第一个索引中,在我的myshapes 向量的第一个索引内,我该怎么做?

在伪代码中它看起来像这样,i 是索引:

myshapes[i].vector[i] = 4;   // but I know this is incorrect

使用 STL 列表是否会更容易实现?如果是,该语法是什么样的?

感谢您的帮助,我是矢量新手,所以任何建议都将不胜感激。

【问题讨论】:

  • 您需要将i 替换为循环中使用的实际变量。也许myshapes[0].vector[0]=4;
  • myshapes[index of shape].verts[index of vertex within that shape]
  • 语法与std::list相同;区别在于它们在不同场景下的实现和性能。
  • std::vector[] 仅用于读取(右值),即数据可用。在使用 std::vector.push_back 或其他函数读取数据之前,您必须将数据添加到向量中。
  • @qxz,对不起,std::vector::operator[] 不仅适用于右值,我错了。我的意思是他应该首先使用 push_back 或其他功能来添加项目。您不能使用 operator[] 在数组中添加新项目。只是考虑到他是矢量的新手。

标签: c++ vector stl


【解决方案1】:

vector 支持使用[] 运算符。语法和语义与对数组使用 [] 运算符非常相似。请参阅:http://en.cppreference.com/w/cpp/container/vector/operator_at

与任何结构成员一样,您需要按名称访问它。 myshapes[i].verts[j] = 4;.

给出的一般建议是使用std::vector 作为您选择的默认容器。当然,如果您有特定需求(例如在容器中间添加/删除项目),其他容器可能具有更好的性能特征。

【讨论】:

  • 感谢您的快速响应。即使你从一个空的形状向量开始,这也能工作吗?我认为它不会因为您评论中的“i”和“j”不存在。如果 'vector myshapes' 开始是空的,并且 shape 结构内的 'vector verts' 也是空的,你是否必须使用 '.push_back()' 来添加第一项?如果是这样,这是正确的语法:'myshapes.push_back().verts.push_back(我要存储的值)'还是这样:'myshapes.push_back(verts.push_back(我要存储的值))'?
  • 对于格式不正确的评论感到抱歉。我想说的是,如果它们最初都是空向量, [] 不起作用吗?在这种情况下,您必须使用推回吗?如果是正确的语法myshapes.push_back().verts.push_back(value I want to store) 还是myshapes.push_back(verts.push_back(value I want to store)) 或两者都不正确?
【解决方案2】:

如果您的向量一开始是空的,您必须先向其中添加元素,然后才能使用operator[] 对其进行索引。这通常使用push_back(添加现有的shape 对象)或emplace_back(直接在向量中构造新的shape 对象)来完成。

鉴于vector&lt;shape&gt; myshapes,您可以添加一些这样的形状:

// add 10 shapes
for (size_t n = 0; n < 10; n++) {
    shape s; // creates a new, blank shape object

    // initialize the shape's data
    s.type = ...;
    s.shapeSize = ...;
    // etc.

    // add verts
    s.verts.push_back(1.0f);
    s.verts.push_back(2.0f);
    s.verts.push_back(3.0f);
    // etc.

    // add the shape to the vector
    myshapes.push_back(std::move(s));
}

(由于我们在最后一行完成了s,我们可以使用std::move。这允许push_back 将形状的数据移动到向量中,而不是复制它。查看移动语义了解更多信息。)

一旦你在向量中有东西,你可以像这样按索引访问元素:

myshapes[index of shape].verts[index of vertex within that shape]

[] 与无效索引一起使用或当向量为空时会调用未定义的行为(不要这样做,否则您的程序将崩溃/出现故障)。

【讨论】:

    猜你喜欢
    • 2020-12-01
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多