我需要这个程序的一些帮助。我是第一次编程课程,并试图让我的程序工作。我已经包含了我到目前为止所写的内容,但它仍然没有编译。它提供了错误: argument list for class template "std::vector" is missing
。
以下是问题:
当您阅读长文档时,很可能会多次出现多个单词。不是存储每个单词,而是仅存储唯一单词并将该文档表示为指向唯一单词的指针的向量可能是有益的。编写实现此策略的程序。从cin
开始一次读一个单词。保留vector <char *>
个单词。如果此向量中不存在新单词,则分配内存,将单词复制到其中,然后将指针附加到新内存。如果该单词已存在,则附加指向现有单词的指针。
以下是代码段:
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
/* Create a vector of char pointers to hold the individual words.
Create a string input to hold the next input through cin. */
int main() {
vector words;
string input;
/* Keep the while loop running using cin as the condition to read an entire document.
This will end when a document has reached its end. */
while (cin >> input) {
/* For every word read as a string, convert the word into a c-string by allocating
a new character array with the proper size and using c_str and strcpy to copy
an identical c-string into the memory heap. */
char* temp = new char[input.length() + 1];
strcpy(temp, input.c_str());
/* Next, check if the word is already in the words array. Use a boolean variable
that updates if the word is found. Compare words by using the strcmp function;
when they are equal, strcmp equals 0. */
bool already_present = false;
for (int i = 0; i < words.size(); i++) {
if (strcmp(temp, words[i]) == 0) {
already_present = true;
}
}
/* If the word is already present, delete the allocated memory.
Otherwise, push the pointer into the words vector. */
if (already_present) {
delete temp;
} else {
words.push_back(temp);
}
}
}
答案 0 :(得分:0)
我希望下面的代码段可能会有所帮助:
#include <string>
#include <iostream>
#include <string.h> // String.h for strcmp()
#include <vector> // Vector Header file is added
using namespace std;
int main() {
vector <char *> words; // vector of char *
string input;
while (cin >> input) {
char *temp = new char[input.length() + 1];
strcpy(temp, input.c_str());
bool already_present = false;
for (unsigned int i = 0; i < words.size(); i++) {
if (strcmp(temp, words[i]) == 0) {
already_present = true;
}
}
if (already_present) {
delete temp;
} else {
words.push_back(temp);
}
}
/* Print the desired output */
for(unsigned int i=0; i<words.size(); i++) {
cout << words[i] << endl;
}
return 0;
}
任何疑问,评论最受欢迎。
编辑:阅读完评论后,我得出结论,您使用的是Microsoft Visual Stdio。请注意,您收到警告的原因是strcpy()
可能不安全,因为如果您尝试将字符串复制到不足以容纳它的缓冲区,则可能导致缓冲区溢出。
暂时考虑一下代码段:
char foo[10]; /* a buffer able to hold 9 chars (plus the null) */
char bar[] = "A string longer than 9 chars";
strcpy( foo, bar ); /* compiles ok, but VERY BAD because you have a buffer overflow
and are corrupting memory. */
strcpy_s()
更安全因为你必须明确指定目标缓冲区的大小,所以函数不会溢出:
strcpy_s( foo, 10, bar ); /* strcpy_s will not write more than 10 characters */
此strcpy_s()
的限制是,它是非标准且MS特定的。因此,如果您编写代码来使用它,您的代码将不再可移植。