首页 > 解决方案 > 如何在 C++ 中更改特定的坐标向量?

问题描述

这是我正在处理的代码:

#include <inq/inq.hpp>
#include <iostream>
#include <fstream>
#include <input/parse_xyz.hpp>

int main(int argc, char **argv) {
  using namespace inq;
  using namespace inq::magnitude;

  input::environment env(argc, argv);
  auto comm = boost::mpi3::environment::get_world_instance();

  auto atoms = input::parse_xyz("zr.xyz");
  //atoms.push_back("Zr" | input::coord(4.8585, 7.01264, 5.172));

  auto box = input::cell::orthorhombic(9.717_A, 11.22023_A, 5.172_A);

  systems::ions ions(box, atoms);
  systems::electrons electrons(comm, ions, input::basis::cutoff_energy(30.0_Ha));
  ground_state::initial_guess(ions, electrons);

  auto result = ground_state::calculate(ions, electrons, input::interaction::pbe(), input::scf::scf_steps(200));

    double const d_0   = 9.77366;
    double const del   = 0.3257886667;
    int    const n_max = 30;


    std::ofstream ofs{"Zr_e_vs_d5.dat"};

    for(int n = 0; n != n_max; ++n){
        double const distance = d_0 - n*del;
        atoms.push_back("Zr" | input::coord(9.18123, 13.2519, distance));
        auto result = ground_state::calculate(ions, electrons, input::interaction::pbe(), input::scf::scf_steps(15));
        //ofs << distance << '\t' << zr_energy(distance) << '\n';
    ofs << distance << '\t' << result.energy.total() << '\n';
    }
 }

我从 .xyz 文件中读取了 50 个原子坐标。然后我在下面的循环中将一个额外的原子推入向量中。我想改变原子的最后一个坐标(Z坐标),从而模拟原子在Z方向移动。我对 C++ 很陌生,不知道如何更改该特定坐标。请帮忙

这是供参考的输入 .xyz 文件:

Zr    0.000000    1.870038    2.586000
Zr    9.717000    1.870038    2.586000
Zr    1.619500    4.675094    2.586000
Zr    0.000000    0.000000    0.000000

标签: c++vectorstdvector

解决方案


在向量中查找特定元素的一般方法是使用find(). 您需要将 包含<algorithm>在您的文件中。

auto ref = find(v.begin(), v.end(), element);

如果 ref 不在向量末尾的下一个,这意味着找到了元素,则相应的索引将是:

if(ref != v.end()){
    int index = ref - v.begin();
}

现在您可以访问和更改向量中索引处的元素,如下所示:

v.at(index) = newCoOrdinate;

这将满足您的要求。


推荐阅读