【发布时间】:2013-10-18 00:48:56
【问题描述】:
我正在尝试创建一个程序,该程序接受文件的输入,然后将单词存储到向量中,到目前为止,我已经让它与 std::vector 类一起使用,尽管我想尝试让我的拥有,使用。但是我遇到了很多错误,不知道如何解决。
错误信息:
main.cpp:43: error: expected constructor, destructor, or type conversion before "Vector"
main.cpp:43: error: expected `;' before "Vector"
main.cpp:47: error: expected constructor, destructor, or type conversion before "Vector"
main.cpp:47: error: expected `;' before "Vector"
main.cpp:55: error: expected constructor, destructor, or type conversion before "Vector"
main.cpp:55: error: expected `;' before "Vector"
main.cpp: In function `int main(int, char**)':
main.cpp:115: error: expected primary-expression before "auto"
main.cpp:115: error: expected `;' before "auto"
main.cpp:116: error: expected primary-expression before "auto"
main.cpp:118: error: no matching function for call to `std::vector<WordInfo, std::allocator<WordInfo> >::push_back(std::string&, int)'
我的代码:
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct WordInfo {
string text;
int count;
};
template <class T> class Vector {
public:
typedef T* iterator;
Vector();
iterator begin();
iterator end();
int size();
iterator insert(iterator position, const T& item);
void alloc_new();
private:
T items[1000];
int used;
};
template <class T> Vector<T>::Vector() {
used = 0;
}
template <class T> Vector<T>::iterator Vector<T>::begin() {
return items;
}
template <class T> Vector<T>::iterator Vector<T>::end() {
return items + used;
}
template <class T> int Vector<T>::size() {
return used;
}
template <class T> Vector<T>::iterator Vector<T>::insert(iterator position, const T& item) {
if (used + 1 > items) {
alloc_new();
}
items[position] = item;
used = +1;
}
template <class T> void Vector<T>::alloc_new() {
items = used * 2;
T tmp[] = items;
for (int i = 0; i < used; i++) {
tmp[i] = items[i];
}
delete items;
items = tmp;
}
/*
*
*/
int main(int argc, char** argv) {
enum {
total, unique, individual
} mode = total;
for (int c; (c = getopt(argc, argv, "tu")) != -1;) {
switch (c) {
case 't': mode = total;
break;
case 'u': mode = unique;
break;
case 'i': mode = individual;
break;
}
}
argc -= optind;
argv += optind;
string word;
vector<string> list;
int count = 0;
int count2 = 0;
while (cin >> word) {
count += 1;
if (find(list.begin(), list.end(), word) != list.end()) {
list.push_back(word);
}
}
switch (mode) {
case total: cout << "Total " << count << endl;
break;
case unique: cout << "Unique " << count2 << endl;
break;
case individual:
vector<WordInfo> list;
while (cin >> word) {
if (find(list.begin(), list.end(), word) != list.end()) {
auto = find(list.begin(), list.end(), word);
list.at(auto).count++;
} else {
list.push_back(word, 1);
}
}
break;
}
return 0;
}
任何帮助将不胜感激,在此先感谢您!
【问题讨论】:
-
您可能希望首先确定它是矢量还是矢量。
-
alloc_new没有工作的希望;该类包含一个数组,而不是指向动态分配数组的指针。 -
您有什么理由不使用标准库中的适当数据结构吗?因为您目前的尝试非常混乱。在尝试同时实现这些数据结构之前,最好弄清楚如何使用标准解决方案来做你想做的事
-
我有added a demo关于如何使用
std::map和标准库算法来实现预期功能 -
另外请注意,您的 getopt 实际上还不允许用户传递
-i。也修复了这个问题