c++ - vector 复制值

标签 c++ c++11 vector stl language-design

<分区>

先手下留情,我是C++初学者

我为我的解释器编写了这段代码:从源代码中读取一行并将行拆分为单词。我使用 vector 对象来存储单词。这是代码,源是文件描述符(ifstream):

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

typedef unsigned int UIntegerP;
#define V(X, Y, Z) X##Y##Z
#define Version V(0, 0, 1)

#define Free 0x0

int main(int ACount, char *Arguments[]){
    if(ACount < 2){
        cout << "Venus Interpreter - Engine V: " << Version << " - Interprate: -I <Source> \n";
    }else{
        if(Arguments[1][0] == '-' && Arguments[1][1] == 'I'){
            if(ACount < 3){
                cout << "Error: No input files \n";
            }else if(ACount > 3){
                cout << "Error: Too much arguments \n";
            }else{
                ifstream Source(Arguments[2]);
                if(Source.good()){  
#                   define __TEST__ 1

                    string Line; 
                    vector<string> Words; 
                    string Word; 

                    while(getline(Source, Line)){ 
                        for(unsigned long Index = 0; Index <= Line.length(); Index++){
                            if(Line[Index] == ' ' or Line[Index] == '\0'){
                                Words.push_back(Word); //Inject the Word to Words
                                Word.clear();
                            } else {
                                Word += Line[Index];
                            }
                        }

#                       if __TEST__
                           cout << Words[0] << "\n";
#                       endif

                        //Interpration starts here
                        Words.clear();  
                    }
                }else{
                    cout << "Error: File does not exist \n";
                }
                Source.close();
            }
        }else{
            cout << "Error: Unknown operand \n";
        }
    }
    return 0;
}

这是程序解释的文件:

10 * 20 / 5 * 10
Asparagas

这是输出:

10
10

正如您在此处看到的,值是重复的。有什么问题?

最佳答案

你的问题是,对于 10 * 20/5 * 10 行,你将单词插入 vector ,然后打印出它的第一个元素

#if __TEST__
    cout << Words[0] << "\n";
#endif

然后您(我假设)认为您正在使用以下行清除 vector

Words.empty();  

但是,这并没有清除 vector ,它返回一个 bool 值,显示 vector 是否为空 (documentation on vector.empty())

要清除 vector ,您应该使用 vector.clear()

第二次在你的循环中,当你处理 asparagus 时,你打印 vector 中的第一个元素,即 10,因为它仍然在 vector 中从第一个 getline

关于c++ - vector 复制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38534231/

相关文章:

c++ - libpq:我应该使用哪些 lib 文件

c++ - 仅在 C++ 标准中阐述?

C++,尝试编写对象读取器,尝试从一个 vector 获取数据时出错

c++ - vector 迭代器根据条件删除两个元素

c++ - curl回调函数线程

android - 在 Android NDK 中使用比 Android Manifest 中的最低 API 更高的 API 是否有效?

c++ - 带位的长枚举

c++ - C++ 0x中的线程析构函数与boost

C++ RTTI 注册表模式

c++ - 将 unique_ptr 添加到 vector 中的类会导致 3 倍 boost