【问题标题】:C++ Use the methods of vector with a structC++ 使用带有结构的向量的方法
【发布时间】:2020-04-21 09:17:19
【问题描述】:

我想做这样的事情。你能帮帮我吗:) 谢谢

/* Example: */

struct Name
{
 const char *full_name;
 const char *name;
};

std::vector<Name> n = { {"Harry Potter", "Harry"}, {"Hermione Granger", "Hermione"} };

// The expressions below does not work

string::const_iterator b = n.begin();
string::const_iterator e = n.end();
int s = n.size();
// ...

【问题讨论】:

  • 什么不起作用?你想做什么?请更具体,目前还不清楚问题是什么
  • 你为什么不使用std::string
  • string::const_iterator b = n.begin(); 没有意义。 n 是一个std::vector&lt;Name&gt;,它与string 没有任何联系
  • 我无法使用方法,开始,结束等...我在编译过程中出错xD
  • '不可能做这样的事情 n.name.begin() ?

标签: c++ vector methods struct


【解决方案1】:

问题主要来自于:

 string::const_iterator b = n.begin(); // not possible
 string::const_iterator e = n.end(); // not possible
 int s = n.size(); // working as intended if you print it to the console

如果你想声明一个迭代器,在这种情况下,你可以这样做:

std::vector<Name>::const_iterator it;

如果您想控制迭代器,请在 for 循环中使用它:

for (it = n.begin(); it != n.end() - 1; it++) // Will stop at the first name in our example
{
    std::cout << it->full_name << std::endl;
}

因为它指向 n,为了访问它的值,不要忘记使用 ->。

如果你想遍历整个向量,可以使用一个简单的循环。`

for (auto i: n)
    {
        std::cout << "My name is " << i.name << ", ";
        std::cout << i.full_name << std::endl;
    }`

附带说明,在 for 循环中使用它之前,您不需要声明“它”。 以下方法也可以:

for (auto it = n.begin(); it != n.end() - 1; it++) // Will stop at the first name in our example 
{
    std::cout << it->full_name << std::endl;
}

作为参考,这是我的最终代码示例,希望能解决您的问题:

  struct Name
{
     std::string full_name;
     std::string name;
};


int main()
{
     std::vector<Name> n = { {"Harry Potter", "Harry"}, {"Hermione Granger", "Hermione"} }; 

     std::vector<Name>::const_iterator it;
    for (auto i : n) // Printing the whole vector
    {
        std::cout << "My name is " << i.name << ", ";
        std::cout << i.full_name << std::endl;
    }

    for (it = n.begin(); it != n.end() - 1; it++) // will return all the names except the last
    {
        std::cout << it->full_name << std::endl;

    }

    for (auto g = n.begin(); g != n.end() - 1; g++) // same as it, iterator initialized in the loop
    {
        std::cout << g->full_name << std::endl;
    }

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多