【问题标题】:C++: Problems with Vectors in a loopC++:循环中的向量问题
【发布时间】:2013-11-12 06:23:27
【问题描述】:

CreateList 函数必须: 1. 向用户询问杂货店名称。 2. 要求用户输入该杂货店的商品列表,直到用户输入“完成”。 3. 将项目添加到输入的字符串向量中。 4. 显示:“已将项目添加到杂货店名称列表。”输入每个项目后,其中“项目”是输入的项目,“杂货店名称”是上面步骤 1 中输入的名称。

void CreateList()
{   
    string store;
    string item;
    int count = 0;
    cout<<"What is the grocery store name"<<endl;
    cin>>store;
    vector<string> store;
    cout<<"Enter a list of items for this grocery store one at a time. When you are done, type done."<<endl;
    cin>>item;
    store[count] = item; //error saying no conversion?
    count++;
    cout<<"Added "<<item<<"to "<<store<<"list"<<endl;
    bool finished=true;
    while (finished = true)
    {
        cout<<"Enter a list of items for this grocery store one at a time. When you are done, type done."<<endl;
        cin>>item;

        if (item == "done")
        break;

        store[count] = item; //error saying no conversion?
        count++;
        cout<<"Added "<<item<<"to "<<store<<"list"<<endl;
}


}

对我的函数有几个问题,不确定无转换错误来自哪里,这可以在 do while 循环中实现吗?请尽量让你的答案尽可能简单,这是我在从 python 过渡时第一次尝试 C++。感谢您的宝贵时间。

【问题讨论】:

  • finished = true - 这是一个任务,并不是你实际上将它设置在任何地方,
  • 不能编译,是吗?您在同一范围内有一个名为 store 的字符串和一个名为 store 的 vector
  • 错误信息应该很清楚
  • 你意识到你声明了两次store
  • 这不会使向量成为存储中保存的名称吗?

标签: c++ function vector while-loop


【解决方案1】:

那里有很多错误。首先,如您所见,您将大量代码重复两次。这表明您应该重构代码。您对do {} while() 的直觉是正确的,您绝对应该使用它。

其次,您不会像在store[count] 中那样通过operator[] 将新项目推入向量中。您应该使用store.push_back(item)store.emplace_back(item)。矢量是一个动态容器,因此一旦创建它就不包含任何元素。尝试使用 store[0] 访问第一个元素将导致未定义的行为,并且很可能会导致分段错误。

第三,正如您所看到的,您也没有真正使用 finished 变量(实际上,您使用 finished = true 分配它并且没有检查它是否为真,那就是 finished == true)。因为您使用break 正确地退出了循环。因此,您绝对应该删除它。

第四,您将商店名称命名为store,并使用相同的名称来声明商店列表向量。您不应该在同一代码块中为两种不同的类型使用相同的名称。

最后,我看到您正在使用类似于using namespace std; 的东西。虽然这对于这种练习来说是可以的,但我认为习惯于在标准库类前面加上 std:: 或者谨慎地只“包含”你真正需要的命名空间是个好主意:

using std::string;
using std::cout;
// ...

这主要是因为各种原因“污染”了全局命名空间is considered bad practice

按照上面的指南,您可以获得类似于:

void CreateList() {  
    std::string store;
    std::string item;
    std::cout << "What is the grocery store name" << std::endl;
    std::cin >> store;

    std::vector<std::string> store_list;
    do {
        std::cout << "Enter a list of items for this grocery store one at a time. When you are done, type done." << std::endl;
        std::cin >> item;
        if (item == "done") break;
        store_list.emplace_back(item);
        std::cout << "Added " << item << "to " << store << "list" << std::endl;
    } while (true);
}

【讨论】:

    【解决方案2】:

    好吧,vector 是一个动态数组,但与标准数组不同,您可以使用 [] 运算符访问指定索引的值,因为矢量重载了 [] 运算符。但是它返回的是你需要的const数据,你不能通过[]来添加或修改数据。 您应该使用“store.push_back(item)”将项目添加到向量中,并且您不需要使用变量来保存总计数,向量将为您保存当前计数。您只需要调用“store.size()”即可获得总数。如果要修改指定索引的数据,可以使用“store.at(index) = value;”修改它。这是正确的代码:

    void CreateList()
    {   
        string storename; // use another name because you use store again below.
        string item;
        int count = 0;
        cout<<"What is the grocery store name"<<endl;
        cin>>storename;
        vector<string> store;
        cout<<"Enter a list of items for this grocery store one at a time. When you are done, type done."<<endl;
        cin>>item;
        **store.push_back(item);** //error saying no conversion?
        count++;
        cout<<"Added "<<item<<"to "<<store<<"list"<<endl;
        bool finished=true;
        while (finished == true)  // Here is not correct, use == to compare, not =. In fact , you use break to quit the loop, so you can just use while(1) or while(true) here. 
        {
            cout<<"Enter a list of items for this grocery store one at a time. When you are done, type done."<<endl;
            cin>>item;
    
            if (item == "done")
            break;
    
            **store.push_back(item);** //error saying no conversion?
            count++;
            cout<<"Added "<<item<<" to "<<storename<<" list"<<endl;
        }
    }
    

    【讨论】:

      【解决方案3】:

      首先,您有 2 个不同的循环来读取您的值,但两者或多或少都损坏了,应该是一个循环。

      此外,您在第二个循环中获得了一个赋值,并声明了两个不同的变量,名称为 store,一个是 string,另一个是 vector&lt;string&gt;。同一范围内不能有 2 个同名的不同变量。

      我认为你真正想做的事情是这样的:

      vector<string> CreateList()
      {   
          string store;
          string item;
          cout<<"What is the grocery store name"<<endl;
          cin>>store;
          vector<string> store_list;
          cout<<"Enter a list of items for this grocery store one at a time. When you are done, type done."<<endl;
      
          while (cin>>item && item != "done") // read next item as long as input didn't fail and item isn't "done".
          {
              store_list.pushback(item); // using pushback for adding new item
              cout<<"Added "<< item <<"to "<< store << " list"<<endl;
          }
      
          return store_list
      
      }
      

      您可能还想以某种方式返回商店列表。

      【讨论】:

        【解决方案4】:

        您有两个名为 store 的变量。一个是字符串,一个是字符串向量。然后,您似乎混淆了这两者,将item 分配给store[count],它描述了一个字符而不是一个字符串,然后尝试输出产品列表,认为它是一个单一的字符串。

        使变量名有意义应该可以修复您的代码:

        void CreateList()
        {   
            std::string storeName;
            std::cout << "What is the grocery store name" << std::endl;
            std::cin >> storeName;
        
            std::cout << "Enter a list of items for this grocery store one at a time. When you are done, type done." << std::endl;
        
            std::vector<std::string> products;
            while (true)
            {
                std::string product;
                std::cin >> product;
        
                if (product == "done")
                    break;
        
                products.push_back(product);
        
                std::cout << "Added " << product << " to " << storeName << " list" << std::endl;
            }
        }
        

        C++ 继承了 C 编程的一个人工制品,它允许您用同名的不同变量“隐藏”一个变量。

        #include <iostream>
        
        int i = 20;
        
        int main() {
            int i = 10;
            for (int i = 0; i < 5; ++i) {
                std::cout << "loop i = " << i << std::endl;
            }
            std::cout << "i = " << i << std::endl;
        }
        

        现场演示:http://ideone.com/eKayzN

        【讨论】:

        • 在他的例子中,变量根本没有shadowed。两个stored 变量在同一个作用域块中声明。不像您在此处显示的示例(其中两个 is 一个在 main 代码块中,另一个在 for 循环中。
        • @Jefffrey 这仍然是阴影,但 ideone 的 GCC 选项将其提升为错误,因此我没有费心重新演示它。
        • 另外,在我的演示中还有第三个“i”,即#include 和 main 之间的全局。请参阅ideone.com/eJ3olP 以升级为重新声明。
        • 所以你是说在同一个作用域中同名的两个变量是合法的
        • 我无法确定它是否合法——我只需要在人们在编译器上解决问题之前解决问题。
        猜你喜欢
        • 2021-10-27
        • 2011-08-17
        • 1970-01-01
        • 1970-01-01
        • 2021-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多