我试图更多地了解STL容器;现在,我已经阅读并使用了std::back_insert_iterator
,所以我想创建一个类似的类仅用于教育目的:
template <typename container>
class BackInsertIter {
public:
BackInsertIter() = delete;
explicit BackInsertIter(container&);
BackInsertIter& operator*();
BackInsertIter& operator=( typename container::const_reference);
container* container_;
};
template <typename container>
BackInsertIter<container>::BackInsertIter(container& cont) :
container_(&cont){
}
template <typename container>
BackInsertIter<container>& BackInsertIter<container>::operator*() {
return *this;
}
template <typename container>
BackInsertIter<container>& BackInsertIter<container>::operator=(typename container::const_reference val) {
container_->.push_back(val);
return *this;
}
template <typename container>
BackInsertIter<container> Back_Insert(container& cont) {
return BackInsertIter<container>(cont);
}
int main() {
std::vector<int> vi;
BackInsertIter< std::vector<int>> bivi(vi);
*bivi = 57;
*bivi = 10;
*bivi = 24;
*bivi = 81;
for (auto i : vi)
std::cout << i << ", ";
std::cout << std::endl;
std::list<std::string> lstr;
BackInsertIter<std::list<std::string>> bilstr(lstr);
*bilstr = "Hello to";
*bilstr = "C++";
*bilstr = "World!";
for (const auto& str : lstr)
std::cout << str << " ";
std::cout << std::endl;
vi.clear();
auto it1 = Back_Insert(vi);
*it1 = 1;
*it1 = 2;
*it1 = 3;
*it1 = 4;
*it1 = 5;
for (auto i : vi)
std::cout << i << ", ";
std::cout << std::endl;
auto it2 = Back_Insert(lstr);
*it2 = "Ahmed";
*it2 = "Programmer";
for (const auto& str : lstr)
std::cout << str << " ";
std::cout << std::endl;
vi.clear();
std::cout << "enter integer values for vector folloed by endline character (ctrl+z): " << std::endl;
std::copy(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(),
Back_Insert(vi));
for (const auto& i : vi)
std::cout << i << " ";
std::cout << std::endl;
}
在我尝试将我的Back_Insert_Iterator
传递到std::copy
并出现此错误的地方,代码才能正常工作:
“严重性代码描述项目文件行 错误C4996'std :: _ Copy_impl':使用参数可能不安全的函数调用-此调用依赖于调用者检查传递的值是否正确。要禁用此警告,请使用-D_SCL_SECURE_NO_WARNINGS。请参阅有关如何使用Visual C ++'Checked Iterators'ConsoleApplication1 c:\ program files(x86)\ Microsoft Visual Studio 14.0 \ vc \ include \ xutility 2230的文档 “