c++ - Vector - 返回部分存储值?

标签 c++ class vector

我在网络上的任何地方都找不到这个,所以我很可能不是解决问题的正确方法,但也许:

我得到了一个具有值 AB 的类,我将这两个值存储在一个集合 vector 中。有没有办法只从 vector 中访问值 A?还是我必须为这些值创建单独的 vector ?

有人想看我的部分代码,所以在这里:

class Read{
    friend ostream &operator<<(ostream &,const Read &);
    public:
        Read(char,float,float,float);
        ~Read();
    private:
        char objekt_;
        float x_, y_, r_;
};

int main(){
    vector<Read> v_read;

    while(fin >> objekt >> x >> y >> r){
        v_read.push_back(Read(objekt, x, y, r));
    }

    return 0;
}

从该 vector 中,我想访问 vector 每个部分中的 objekt_ 值。

最佳答案

给定一个包含两个元素的struct vector ,我们可以做如下事情:

#include <vector>
#include <algorithm>
#include <boost/bind.hpp>
#include <iterator>
#include <iostream>

struct test {
  int a;
  double b;
};

int main() {
  std::vector<test> vec = {{0, 0.1}, {1, 0.2}};

  // Copy the a's to another iterator
  std::transform(vec.begin(), vec.end(),
                 std::ostream_iterator<int>(std::cout, "\n"),
                 boost::bind(&test::a,_1));

  // and the b's to another iterator
  std::transform(vec.begin(), vec.end(),
                 std::ostream_iterator<double>(std::cout, "\n"),
                 boost::bind(&test::b,_1));

  // or just copy them into another vector
  std::vector<int> veca;
  veca.reserve(vec.size());
  std::transform(vec.begin(),vec.end(),
                 std::back_inserter(veca),
                 boost::bind(&test::a,_1));
}

对于给定 std::vector 中的所有条目,仅使用每个结构的一部分。

关于c++ - Vector - 返回部分存储值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8697352/

相关文章:

c++ - 如何使用 CSpinButtonCtrl 类在 MFC 中动态创建旋转按钮控件?

C++:从二进制文件读取输入时出现问题

c++ - 面对抛出移动构造函数/赋值运算符,std::vector::emplace() 是否真的提供了强大的异常保证?

c++ - 如何实现最大堆

c++ - 为什么 std::forward 不能自己推导模板参数?

python - 使 python @property 句柄 +=, -= 等

.net - VB.NET需要一个class属性才能成为列表数组

c++ - 如何在 C++ 中对成对 vector 的第二个元素执行 lower_bound 操作?

c++ - 如何将谓词作为函数参数传递

c++ - 具有 boost 1.56 的卡萨布兰卡因 -Werror 而失败